iggrouping的实现类是什么?
本文关键字:是什么 实现 iggrouping | 更新日期: 2023-09-27 18:18:03
我正在尝试创建一个WCF数据服务ServiceOperation,在服务器端进行分组,然后将数据发送到客户端。
当我尝试调用它(甚至连接到服务)时,我得到一个错误。它说它不能构造接口。
我使用的唯一接口是iggrouping。
这个接口的实际类是什么?
更新:
我在调试一个示例应用程序时检查了类型,它告诉我它是:
System.Linq.Lookup<TKey,TElement>.Grouping
但是它在什么汇编中呢?
BCL中有几个类型实现了IGrouping
,但是它们都是内部的,只能通过IGrouping
接口访问。
但是IGrouping
仅仅是带有关联键的IEnumerable<TElement>
。您可以轻松地实现由List<TElement>
支持的IGrouping
,并且应该不难跨调用边界序列化:
public class Grouping<TKey, TElement> : IGrouping<TKey, TElement> {
readonly List<TElement> elements;
public Grouping(IGrouping<TKey, TElement> grouping) {
if (grouping == null)
throw new ArgumentNullException("grouping");
Key = grouping.Key;
elements = grouping.ToList();
}
public TKey Key { get; private set; }
public IEnumerator<TElement> GetEnumerator() {
return this.elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
应用GroupBy
操作符后,您可以创建Grouping
实例列表:
var listOfGroups =
source.GroupBy(x => ...).Select(g => new Grouping<TKey, TElement>(g)).ToList();
这可能是iggrouping最基本和最通用的实现。它的构造函数接受一个键和一组值。
public class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
{
private readonly TKey key;
private readonly IEnumerable<TElement> values;
public Grouping(TKey key, IEnumerable<TElement> values)
{
if (values == null)
throw new ArgumentNullException("values");
this.key = key;
this.values = values;
}
public TKey Key
{
get { return key; }
}
public IEnumerator<TElement> GetEnumerator()
{
return values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
我用一个示例应用程序检查了类型,它是:
System.Linq.Lookup<TKey,TElement>.Grouping
。但是它在哪个集合里呢?
类型嵌套在System.Linq.Lookup<TKey,TElement>
;System.Core
程序集内部。
var groupingType = "1".GroupBy(x => x).Single().GetType().GetGenericTypeDefinition();
Console.WriteLine("Type: " + groupingType);
Console.WriteLine("Public: " + groupingType.IsPublic);
Console.WriteLine("Assembly: " + groupingType.Assembly);
输出:Type: System.Linq.Lookup`2+Grouping[TKey,TElement]
Public: False
Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
从。net 4.0开始,在核心。net框架中没有实现System.Linq.IGrouping<TKey,TElement>
的公共类型。如果您需要这样的类型(假设它是可序列化的),不幸的是,您可能必须自己滚动一个。