Looping over ILookup, accessing values
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();
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);
}
I create an enumeration using the keys first, which I find easier to follow.
IEnumerable<string> keys = lookupTable.Select(t => t.Key);
foreach(string key in keys)
{
// use the value of key to access the IEnumerable<List<CustomObject>> from the ILookup
foreach( List<CustomObject> customList in lookupTable[key] )
{
Console.WriteLine(customList);
}
}