LINQ group by expression syntax

后端 未结 1 1534
不思量自难忘°
不思量自难忘° 2021-02-02 06:19

I\'ve got a T-SQL query similar to this:

SELECT r_id, r_name, count(*)
FROM RoomBindings
GROUP BY r_id, r_name

I would like to do the same usin

1条回答
  •  清歌不尽
    2021-02-02 06:50

    Try this:

    var rooms = from roomBinding in DALManager.Context.RoomBindings
                            group roomBinding by new 
                            { 
                               Id = roomBinding.R_ID, 
                               Name = roomBinding.r_name
                            }
                            into g
                            select new 
                            { 
                               Id = g.Key.Id,
                               Name = g.Key.Name,
                               Count = g.Count()  
                            };
    

    Edit by Nick - Added method chain syntax for comparison

    var rooms = roomBinding.GroupBy(g => new { Id = g.R_ID, Name = g.r_name })
                           .Select(g => new
                               {
                                   Id = g.Key.Id,
                                   Name = g.Key.Name,
                                   Count = g.Count()
                               });
    

    0 讨论(0)
提交回复
热议问题