Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi I have this code but in fact I dont understant what happen here can any one explain me the code :
C#
ordering.GroupBy(name=> name).OrderByDescending(g => g.Count())

I dont understand (name=>name) and (g=>g.count) help me only in this part
Posted
Updated 4-Jun-12 9:16am
v2

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:

C#
public class t
{
    public string Shortname { get; set; }
    public string Longname { get; set; }
}


Then put this in a console program:

C#
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:

VB
Key = US
  Records
   Long US 1
   Long US 2

Key = UK
  Records
   Long UK 1
 
Share this answer
 
v2
Comments
Sandeep Mewara 5-Jun-12 11:14am    
5!
This is a nice article How does it work in C#? - Part 3 (C# LINQ in detail)[^]

Please read it and it will help you.

Thanks
 
Share this answer
 
Those are lambdas,

C#
name => name

Takes name as an argument and returns name

C#
g => g.count

Takes g as an argument and returns g.Count()

So it groups them by name, then orders them by the number of items in each group.
 
Share this answer
 
this syntax call lambda Expression!
Read this article about lambda Expression syntax[^]
 
Share this answer
 
You need to take a look at the topic LINQ[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900