如何对集合中的重复项进行分组?

发布于 2024-09-13 03:06:52 字数 695 浏览 2 评论 0 原文

我正在创建一个程序,它使用正则表达式解析日志文件中的用户名及其 GUID(全局唯一标识符)。到目前为止,我的程序正确提取了数据,并将其存储在一个两列的数据表中。使用此代码输出其内容:

foreach (DataRow dr in guids.Select("","guid"))
    {
        Console.WriteLine("GUID {0} has the name '{1}'\n", dr["guid"], dr["name"]);
    }

示例输出:

GUID c6c4486 has the name 'Daniel'
GUID c6c4486 has the name 'Mark'
GUID adh2j34 has the name 'Sophie'

工作正常,但我想

GUID c6c4486 has the names 'Daniel' and 'Mark'
GUID adh2j34 has the name 'Sophie'

通过使用多维数组之类的东西来表示:

players['guidhere'][0] = Daniel;
players['guidhere'][1] = Mark;

关于如何解决此问题的任何想法?我应该只使用数组,还是有更动态的东西?

I'm creating a program that parses a log file for a user's name and its GUID (Global unique identifier) using regular expressions. So far, my program extracts the data properly, and stores it in a two-column DataTable. Outputting its content with this code:

foreach (DataRow dr in guids.Select("","guid"))
    {
        Console.WriteLine("GUID {0} has the name '{1}'\n", dr["guid"], dr["name"]);
    }

Example output:

GUID c6c4486 has the name 'Daniel'
GUID c6c4486 has the name 'Mark'
GUID adh2j34 has the name 'Sophie'

Works fine, but I would like it to say

GUID c6c4486 has the names 'Daniel' and 'Mark'
GUID adh2j34 has the name 'Sophie'

by using something like a multidimensional array:

players['guidhere'][0] = Daniel;
players['guidhere'][1] = Mark;

Any ideas on how to approach this problem? Should I just use arrays, or is there anything more dynamic?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝梦月影 2024-09-20 03:06:52

使用 LINQ 的 group 语句,而不是处理成数据表处理成类型化的对象列表:

var grps = from r in resultList
        group r by r.Guid into g
        select new { guid = g.Key, Names = String.Join(" and ", g) };
foreach(var g in grps)
  Console.WriteLine("GUID {0} has the names {1}", g.guid, g.Names);

Instead of processing into a datatable process into a typed list of objects then use LINQ's group statement :

var grps = from r in resultList
        group r by r.Guid into g
        select new { guid = g.Key, Names = String.Join(" and ", g) };
foreach(var g in grps)
  Console.WriteLine("GUID {0} has the names {1}", g.guid, g.Names);
×眷恋的温暖 2024-09-20 03:06:52

LINQ 答案应该可以正常工作,但我有点老式,我想我会选择 Dictionary>。填充后,您可以轻松地循环浏览字典。

The LINQ answer should work fine, but I'm a little more old-fashioned, and I think I'd go with a Dictionary<Guid, List<string>>. Once populated, you can loop through your dictionary pretty easily.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文