简体   繁体   中英

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

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, eg

var query = foo.Where(...)
               .OrderBy(...)
               .GroupBy(...)
               .Select(...)

I think you need:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM