C#中的LINQ的 - GroupedEnumerable用法? [英] c# Linq's - GroupedEnumerable usages?
问题描述
Fruit[] data = new[] {
new Fruit {Name = "Gala",Type = "Apple",Price = 0.75m,Quantity = 10},
new Fruit {Name = "Granny Smith",Type = "Apple",Price = 0.80m,Quantity = 7},
new Fruit {Name = "Tasty",Type = "Strawberries",Price = 1.90m,Quantity = 20}
};
var grouped = from fruit in data
group fruit by fruit.Type;
组合
的类型是: <$c$c>System.Linq.GroupedEnumerable<ConsoleApplication15.Fruit,string,ConsoleApplication15.Fruit>$c$c>
有它的样子:
have a look on it :
我的问题:
如果组合中包含的项目(实现IEnumerable) - 为什么它的类型是 GroupedEnumerable
if grouped contains items ( implements ienumerable ) - why its type is GroupedEnumerable
和不是
IEnumerable <System.Linq.IGrouping<string,ConsoleApplication15.Fruit>>
为什么他们创建一个新的类型又名 GroupedEnumerable
?
推荐答案
如果你有一个的对象的在.NET中,它必须是一些具体的类型,它不能是一个接口。因此,举例来说,新的IList&LT; INT&GT;()
是无效的,你必须做一些像新名单,其中,INT&GT;()
。
If you have an object in .Net, it has to be of some concrete type, it can't be an interface. So, for example, new IList<int>()
is not valid, you have to do something like new List<int>()
.
如果你有一个的变量的,它的类型可以是一个接口,所以你可以写,例如,的IList&LT; INT&GT;名单=新的名单,其中,INT&GT;()
If you have a variable, its type can be an interface, so you can write, for example, IList<int> list = new List<int>()
.
而这正是这里发生了什么。的类型的变量的组合
是的IEnumerable&LT; IGrouping&LT;串,水果和GT;&GT;
(虽然它不是从code清楚,因为你使用 VAR
)。中的对象的由该变量引用的类型是 GroupedEnumerable&LT;水果,串,水果&GT;
,这是由实施的内部类型 GROUPBY()
。它不能是的IEnumerable
,因为你不能有一个接口的实例。
And that's exactly what's happening here. The type of the variable grouped
is IEnumerable<IGrouping<string,Fruit>>
(although it's not clear from the code, because you're using var
). The type of the object referenced by that variable is GroupedEnumerable<Fruit, string, Fruit>
, which is an internal type used by the implementation of GroupBy()
. It can't be IEnumerable
, because you can't have an instance of an interface.
Visual Studio调试器是显示你的对象的运行时类型,因为这是调试器是什么:向您展示了运行时信息
The Visual Studio debugger is showing you the runtime type of the object, because that's what debugger is for: to show you the runtime information.
这篇关于C#中的LINQ的 - GroupedEnumerable用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!