Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq -Extension Method

Tags:

c#

linq

How to use extension methods to form the second query as the first one.

1) var query = from cm in cust
               group cm by cm.Customer into cmr
               select (new { CKey = cmr.Key, Count = cmr.Count() });

(second query is not well formed)

2)    var qry = cust.GroupBy(p => p.Customer).
                Select(new { CKey = p.Key, Count = p.Count }); 
like image 393
Udana Avatar asked Nov 17 '25 20:11

Udana


2 Answers

Try this:

var query = cust.GroupBy(p => p.Customer)
                .Select(g => new { CKey = g.Key, Count = g.Count() });

You can also simplify this into a single call to this GroupBy overload though:

var query = cust.GroupBy(p => p.Customer,
                         (key, g) => new { CKey = key, Count = g.Count() });

Note that I've changed the name of the lambda expression's parameter name for the second line to g - I believe that gives more of a clue that you're really looking at a group rather than a single entity.

I've also moved the dot onto the second line in the form that still uses Select - I find this makes the query easier to read; I usually line up the dots, e.g.

var query = foo.Where(...)
               .OrderBy(...)
               .GroupBy(...)
               .Select(...)
like image 129
Jon Skeet Avatar answered Nov 20 '25 11:11

Jon Skeet


I think you need:

var qry = cust.GroupBy(p => p.Customer)
    .Select(grp => new { CKey = grp.Key, Count = grp.Count() });
like image 38
Lee Avatar answered Nov 20 '25 11:11

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!