开发者

C# Linq -Extension Method

How to use extension methods to form the second query as t开发者_JS百科he 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, e.g.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜