[英]Can I use an anonymous type for this Linq grouping?
I have the following code which produces a dictionary containing multiple lists; 我有以下代码生成包含多个列表的字典; each list can be retrieved with a numeric key. 可以使用数字键检索每个列表。
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);
}
Is there any way to eliminate the IndexedGroup
class? 有没有办法消除IndexedGroup
类?
I've tried using an anonymous type in the Select
method, like this: 我尝试在Select
方法中使用匿名类型,如下所示:
.Select(g => new { Index = g.Key, Children = g })
but I get a type conversion error. 但我收到类型转换错误。
Cast Children
from IGrouping<T>
to IEnumerable<T>
, or explicitly pass generic parameters to the ToDictionary
call. 将Children
从IGrouping<T>
为IEnumerable<T>
,或者将通用参数显式传递给ToDictionary
调用。
The g
parameter is an IGrouping<T>
, which implements IEnumerable<T>
. g
参数是IGrouping<T>
,它实现IEnumerable<T>
。
The implicit generic calls end up creating a Dictionary<int, IGrouping <MyClass>>
, which cannot be converted to a Dictionary<int, IEnumerable <MyClass>>
. 隐式泛型调用最终创建了一个Dictionary<int, IGrouping <MyClass>>
,它无法转换为Dictionary<int, IEnumerable <MyClass>>
。
This is avoided by your IndexedGroup
class, since its Children
property explicitly typed as IEnumerable<MyClass>
. IndexedGroup
类可以避免这种情况,因为它的Children
属性显式地输入为IEnumerable<MyClass>
。
For example:
例如:
return myList.Where(a => a.Group == group) .GroupBy(n => n.GroupIndex) .ToDictionary<int, IEnumerable<MyClass>>(g => g.Key, g => g);
Also, you may be interested in the ILookup<TKey, TElement>
interface . 此外,您可能对ILookup<TKey, TElement>
界面感兴趣。
You could just get rid of the Select()
entirely and call .AsEnumerable()
: 你可以完全摆脱Select()
并调用.AsEnumerable()
:
return myList.Where(a => a.Group == group)
.GroupBy(n => n.GroupIndex)
.ToDictionary(g => g.Key, g => g.AsEnumerable());
Or you could change your return type to an ILookup
, which is basically the data structure you're going for: 或者您可以将返回类型更改为ILookup
,这基本上就是您要使用的数据结构:
public ILookup<int, MyClass> GetIndexedGroups(string group)
{
return myList.Where(a => a.Group == group)
.ToLookup(n => n.GroupIndex);
}
How about the following? 以下怎么样?
return myList.Where(a => a.Group == group)
.GroupBy(n => n.GroupIndex)
.ToDictionary(g => g.Key, g => g as IEnumerable<MyClass>);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.