c# - 我可以为此 Linq 分组使用匿名类型吗?

标签 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);
}

有什么方法可以消除 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/

相关文章:

c# - 如何在 C# 中获取枚举索引值

c# - 使用 IEnumerable GetGenericArguments 获取类型

c# - 延迟执行 - 字典输出

c# - Linq解析html字符串

Javascript 数组分组

Python:具有最常见条目的数据子集

c# - 在 ODATA $metadata 上设置命名空间

c# - Silverlight 应用程序的 WCF 服务返回 "NotFound"

c# - 无法访问已处置的对象错误

r - 为什么在 ave() 中使用 `==` 类整数的结果?