我从我做过的linq中得到了一个ILookup< string, List<CustomObject> >。
现在我想迭代一下结果:
foreach(IGrouping<string, List<CustomObject>> groupItem in lookupTable)
{
groupItem.Key; //You can access the key, but not the list of CustomObject
}我知道我一定是把IGrouping误解为KeyValuePair了,但是现在我不确定如何正确地访问它。
发布于 2014-06-08 05:11:55
ILookup是一个列表列表:
public interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>所以因为IGrouping<TKey, TElement>是(实现的)..。
IEnumerable<TElement>...a查找是
IEnumerable<IEnumerable<TElement>>在本例中,TElement也是一个列表,因此您最终得到
IEnumerable<IEnumerable<List<CustomObject>>>所以这就是你如何在客户之间循环:
foreach(IGrouping<string, List<CustomObject>> groupItem in lookupTable)
{
groupItem.Key;
// groupItem is <IEnumerable<List<CustomObject>>
var customers = groupItem.SelectMany(item => item);
}发布于 2014-06-08 00:09:34
ILookup中的每个条目都是另一个IEnumerable
foreach (var item in lookupTable)
{
Console.WriteLine(item.Key);
foreach (var obj in item)
{
Console.WriteLine(obj);
}
}编辑
一个简单的例子:
var list = new[] { 1, 2, 3, 1, 2, 3 };
var lookupTable = list.ToLookup(x => x);
var orgArray = lookupTable.SelectMany(x => x).ToArray();发布于 2019-11-11 01:08:24
我首先使用键创建一个枚举,我发现这样更容易理解。
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);
}
}https://stackoverflow.com/questions/24099061
复制相似问题