循环查找,访问值
本文关键字:访问 查找 循环 | 更新日期: 2023-09-27 18:07:31
我从我做的一些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
,但现在我不确定如何正确访问它。
ILookup
是列表的列表:
public interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>
所以因为IGrouping<TKey, TElement>
是(实现)…
IEnumerable<TElement>
…查找
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);
}
illookup中的每个条目都是另一个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();
我首先使用键创建一个枚举,我发现这样更容易执行。
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);
}
}