tags:

views:

114

answers:

2

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 });
+8  A: 

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(...)
Jon Skeet
Jon Thanks for the suggestion.
Udana
Jon,You mean to say the order could be where...OrderBy...GroupBy..,right?
Udana
He means to say that separate all the tags like .where . select into separate lines so that its easy to read :)
Mahesh Velaga
Mahesh is right - those were just sample methods. They could have been entirely different ones.
Jon Skeet
+2  A: 

I think you need:

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