How to groupBy in linq for sql?

I have such data

id = 1<pk> SDate = 12/12/2009 EDate = 12/12/2009 binding = a_1 userid = 14 id = 2<pk> SDate = 12/12/2009 EDate = 12/12/2009 binding = a_1 userid = 14 

I want to group my data by binding. I am not sure how to do this. Should I make a new choice for this?

I still have it

  Db.Table.Where(u => u.UserId == userId && u.Binding == binding) .GroupBy(u => u.Binding) 

So, I want to return all the columns. Should i go

 .select(group = new Table {....}); 
+4
source share
1 answer

Remember that Linq GroupBy is not like SQL GroupBy. Linq GroupBy returns .Key (which is your conditional group) and then IEnumerable <> of what you are grouping. Therefore, if you want to count all the rows for each binding together with the binding itself, this will be:

  var bindingsAndCounts = Db.Table.Where(u => u.UserId == userId && u.Binding == binding) .GroupBy(u => u.Binding) .Select(g => new {g.Key, BindingCount = g.Count()}); 

This is a much more powerful construct than with SQL, because you can do anything with "g" in the expression.

If you want to list each group, you can omit the choice:

 foreach (var group in whateveryourgroupingExpressionWas) { Console.WriteLine(group.Key); foreach (var row in group) { Console.WriteLine("ID: " + row.Id + "Name " + row.Name ...); } } 
+5
source

All Articles