我怎么能从一个集合中复制重复项呢?

时间:2010-08-07 03:37:46

标签: c# regex algorithm parsing collections

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

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;

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

2 个答案:

答案 0 :(得分:4)

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

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);

答案 1 :(得分:0)

LINQ答案应该可以正常工作,但我有点老式,我想我会使用Dictionary< Guid,List< string>>。填充后,您可以非常轻松地遍历字典。