You might understand this better by the following
name => name
is the same as
f(name) = name
, just that you do not need to include a function name (in this care the function name is
f
)
Therefore the first
ordering.GroupBy(name => name)
is saying that you want the grouping to be according the the name. Now this code creates a key that in this case only has the
name
and a collection of records (objects) that have the same
name
.
What is happening in the second part is that you are counting the records under each record which is a collection of original records that have the same key, or in this case are the same string. As a function this would be
f(keyCollection) = keyCollection.Count()
.
This might help:
Define a class:
public class t
{
public string Shortname { get; set; }
public string Longname { get; set; }
}
Then put this in a console program:
var testclass = new t[] {new t {Shortname = "US", Longname = "Long US 1"},
new t {Shortname = "US", Longname = "Long US 2"},
new t {Shortname = "UK", Longname = "Long UK 1"},};
var testLinq = testclass.GroupBy(i => i.Shortname);
foreach (var g in testLinq)
{
Console.WriteLine("Key = " + g.Key);
Console.WriteLine(" Records");
foreach (var r in g)
Console.WriteLine(" " + r.Longname);
Console.WriteLine();
}
Console.ReadLine();
You will get the following:
Key = US
Records
Long US 1
Long US 2
Key = UK
Records
Long UK 1