Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over ILookup, accessing values

Tags:

c#

.net

linq

I've got a ILookup< string, List<CustomObject> > from some linq I've done.

I'd like to now iterate over the results:

foreach(IGrouping<string, List<CustomObject>> groupItem in lookupTable)
{
    groupItem.Key; //You can access the key, but not the list of CustomObject
}

I know I must be misrepresenting a IGrouping as a KeyValuePair, but now I'm not sure how to access it properly.

like image 763
Jono Avatar asked Jun 07 '14 16:06

Jono


1 Answers

ILookup is a list of lists:

public interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>

So because IGrouping<TKey, TElement> is (implements)...

IEnumerable<TElement>

...a lookup is

IEnumerable<IEnumerable<TElement>>

In your case TElement is also a list, so you end up with

IEnumerable<IEnumerable<List<CustomObject>>>

So this is how you can loop through the customers:

foreach(IGrouping<string, List<CustomObject>> groupItem in lookupTable)
{
    groupItem.Key;
    // groupItem is <IEnumerable<List<CustomObject>>
    var customers = groupItem.SelectMany(item => item);
}
like image 85
Gert Arnold Avatar answered Sep 27 '22 16:09

Gert Arnold