Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

grouped type is : System.Linq.GroupedEnumerable<ConsoleApplication15.Fruit,string,ConsoleApplication15.Fruit>

have a look on it : enter image description here

my question :

if grouped contains items ( implements ienumerable ) - why its type is GroupedEnumerable

and not

IEnumerable <System.Linq.IGrouping<string,ConsoleApplication15.Fruit>>

why did they create a new Type aka GroupedEnumerable ?

like image 942
Royi Namir Avatar asked Feb 20 '23 14:02

Royi Namir


1 Answers

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>().

If you have a variable, its type can be an interface, so you can write, for example, IList<int> list = new List<int>().

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.

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.

like image 175
svick Avatar answered Mar 03 '23 23:03

svick