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?
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.
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.
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()
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.
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() });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With