views:

59

answers:

2

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?

+4  A: 

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);
Tahbaza
Could you explain what the select part does? String.Join(g," and ") returns an error
Daniel S
@Daniel S: it looks like the arguments in String.Join are the wrong way around if I remember correctly - the argument " and " should go first. The other thing is that if you're not using .NET 4.0, you'll need to call ToArray() on g to convert the names to an array. And by the way, +1 @Tahbaza.
Alex Humphrey
Sorry all - my String.Join parameters were indeed backwards (doing from my failing memory obviously) - fixed now with an edit
Tahbaza
Thank you! I've just learnt a bit of LINQ :P And it's fucking awesome. I figured out the error by myself aswell. Thanks man :D
Daniel S
A: 

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.

Joe Enos