Rob*_*vey 4 c# linq grouping anonymous-types
我有以下代码生成包含多个列表的字典; 可以使用数字键检索每个列表.
public class myClass
{
public string Group { get; set; }
public int GroupIndex { get; set; }
...
}
public List<MyClass> myList { get; set; }
private Class IndexedGroup
{
public int Index { get; set; }
public IEnumerable<MyClass> Children { get; set; }
}
public Dictionary<int, IEnumerable<MyClass>> GetIndexedGroups(string group)
{
return myList.Where(a => a.Group == group)
.GroupBy(n => n.GroupIndex)
.Select(g => new IndexedGroup { Index = g.Key, Children = g })
.ToDictionary(key => key.Index, value => value.Children);
}
Run Code Online (Sandbox Code Playgroud)
有没有办法消除IndexedGroup班级?
我尝试在Select方法中使用匿名类型,如下所示:
.Select(g => new { Index = g.Key, Children = g })
Run Code Online (Sandbox Code Playgroud)
但我收到类型转换错误.
演员Children从IGrouping<T>到IEnumerable<T>,或者明确地传递泛型参数的ToDictionary调用.
所述g参数是一个IGrouping<T>,它实现IEnumerable<T>.
隐式泛型调用最终创建一个,不能转换为.Dictionary<int, IGrouping<MyClass>>Dictionary<int, IEnumerable<MyClass>>
您的IndexedGroup类可以避免这种情况,因为它的Children属性显式类型为IEnumerable<MyClass>.
例如:
return myList.Where(a => a.Group == group)
.GroupBy(n => n.GroupIndex)
.ToDictionary<int, IEnumerable<MyClass>>(g => g.Key, g => g);
Run Code Online (Sandbox Code Playgroud)
此外,您可能对ILookup<TKey, TElement>界面感兴趣.