开发者

counting items in grouped results in Linq to Sql

开发者 https://www.devze.com 2022-12-09 11:38 出处:网络
I want to 开发者_Python百科group results ofquery by the item id and count number of items in each group. finally i will take only one item from each group and the count of that group to display

I want to 开发者_Python百科group results of query by the item id and count number of items in each group. finally i will take only one item from each group and the count of that group to display

   results.GroupBy(r=>r.ID)....


You can do some grouping in Linq like this:

var items = from r in rows
            group r by r.ID into g
            select new { Count = g.Count(), First = g.First() };

... but that'll give you a collection of objects with a "Count" property (int) and a "First" property (of the same type as your rows).

What you might want to do is select something that's shaped similarly to your row, except with a count property. One way to do that is field by field like this:

var items = from r in rows
            group r by r.ID into g
            let f = g.First()
            select new 
            {
               f.ID, f.Name, f.Foo, f.Bar, // etc
               Count = g.Count()
            };
0

精彩评论

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