How could I group duplicates from a collection?
I'm creating a program that parses a lo开发者_StackOverflowg 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?
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);
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.
精彩评论