Udana
Udana

Reputation: 815

C# Linq -Extension Method

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 }); 

Upvotes: 2

Views: 6055

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499860

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

Upvotes: 12

Lee
Lee

Reputation: 144126

I think you need:

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

Upvotes: 2

Related Questions