Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ group by expression syntax

Tags:

c#

linq

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 using LINQ. So far I got here:

var rooms = from roomBinding in DALManager.Context.RoomBindings                         group roomBinding by roomBinding.R_ID into g                         select new { ID = g.Key }; 

How can I extract the count(*) and r_name part?

like image 360
agnieszka Avatar asked Nov 25 '09 10:11

agnieszka


People also ask

How can we do a GroupBy using LINQ query?

Group by single property example The following example shows how to group source elements by using a single property of the element as the group key. In this case the key is a string , the student's last name. It is also possible to use a substring for the key; see the next example.

Can we use GroupBy in LINQ C#?

You can also use Into Group with GroupBy in VB.Net. LINQ query is ended with the help Select or Groupby clause. It can also support method syntax in both C# and VB.Net languages.

What does GroupBy return in LINQ?

A LINQ query can end with a GroupBy or Select clause. The result of GroupBy operators is a collection of groups. For example, GroupBy returns IEnumerable<IGrouping<TKey,Student>> from the Student collection: Return type of GroupBy()

What is GroupBy in C#?

The group clause returns a sequence of IGrouping<TKey,TElement> objects that contain zero or more items that match the key value for the group. For example, you can group a sequence of strings according to the first letter in each string.


1 Answers

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()                            }); 
like image 52
bruno conde Avatar answered Sep 22 '22 10:09

bruno conde