我有以下代码生成包含多个列表的字典;每个列表都可以使用数字键检索。
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);
}
有什么方法可以消除 IndexedGroup
类吗?
我试过在 Select
方法中使用匿名类型,如下所示:
.Select(g => new { Index = g.Key, Children = g })
但我收到类型转换错误。
最佳答案
投 Children
来自 IGrouping<T>
至 IEnumerable<T>
,或显式将通用参数传递给 ToDictionary
打电话。
g
参数是 IGrouping<T>
, 它实现了 IEnumerable<T>
.
隐式通用调用最终会创建一个 Dictionary<int, <i>IGrouping</i><MyClass>>
, 无法转换为 Dictionary<int, <i>IEnumerable</i><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);
罢工><罢工>罢工>
此外,您可能对 ILookup<TKey, TElement>
interface 感兴趣.
关于c# - 我可以为此 Linq 分组使用匿名类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4380114/