Looping over ILookup, Accessing Values

I have an ILookup< string, List<CustomObject> > from some linq that I made.

Now I would like to 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 that I should distort IGrouping as KeyValuePair , but now I'm not sure how to access it correctly.

+7
c # linq
source share
2 answers

ILookup - list of lists:

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

Since IGrouping<TKey, TElement> (implements) ...

 IEnumerable<TElement> 

... Search

 IEnumerable<IEnumerable<TElement>> 

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

 IEnumerable<IEnumerable<List<CustomObject>>> 

Thus, you can navigate through clients:

 foreach(IGrouping<string, List<CustomObject>> groupItem in lookupTable) { groupItem.Key; // groupItem is <IEnumerable<List<CustomObject>> var customers = groupItem.SelectMany(item => item); } 
+13
source share

Each entry in ILookup is another IEnumerable

 foreach (var item in lookupTable) { Console.WriteLine(item.Key); foreach (var obj in item) { Console.WriteLine(obj); } } 

EDIT

A simple example:

 var list = new[] { 1, 2, 3, 1, 2, 3 }; var lookupTable = list.ToLookup(x => x); var orgArray = lookupTable.SelectMany(x => x).ToArray(); 
+4
source share

All Articles