How way to operate on single items at an index in group in IGrouping?

I have simplified groupby code below, where I know there exists at most two records for each group, with each group being grouped by the value at index two in string a array. I want to iterate through the list of keys in the IGrouping, and combine some values in each Group then add that result to a final list, but I am new to LINQ so don't exactly know how to access these first and/or second values at an index.

Can anyone shed some light on how to do this?

each Group derived from var lines is something like this:

 key    string[]
----   ------------- 
123    A, stuff, stuff
123    B, stuff, stuff

and I want the result to be a string[] that combines elements of each group in the "final" list like:

string[]
-------
A, B

my code:

     var lines = File.ReadAllLines(@path).Skip(1).Select(r => r.Split('\t')).ToList();
     List<string[]> final = new List<string[]>();
     var groups = lines.GroupBy(r => r[2]);

     foreach (var pairs in groups)
     {
        // I need to combine items in each group here; maybe a for() statement would be better so I can peek ahead??
        foreach (string[] item in pairs)
        {
           string[] s = new string[] { };
           s[0] = item[0];
           s[1] = second item in group - not sure what to do here or if I am going aboout this the right way

           final.Add(s);
        }
     }

There's not too much support on the subject either, so I figured it may be helpful to somebody.

Jon Skeet
people
quotationmark

It sounds like all you're missing is calling ToList or ToArray on the group:

foreach (var group in groups)
{
    List<string[]> pairs = group.ToList();
    // Now you can access pairs[0] for the first item in the group,
    // pairs[1] for the second item, pairs.Count to check how many
    // items there are, or whatever.
}

Or you could avoid creating a list, and call Count(), ElementAt(), ElementAtOrDefault() etc on the group.

Now depending on what you're actually doing in the body of your nested foreach loop (it's not clear, and the code you've given so far won't work because you're trying to assign a value into an empty array) you may be able to get away with:

var final = lines.GroupBy(r => r[2])
                 .Select(g => ...)
                 .ToList()

where the ... is "whatever you want to do with a group". If you can possibly do that, it would make the code a lot clearer.

With more information in the question, it looks like you want just:

var final = lines.GroupBy(r => r[2])
                 .Select(g => g.Select(array => array[0]).ToArray())
                 .ToList()

people

See more on this question at Stackoverflow