Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GroupBy with linq method syntax (not query syntax)

Tags:

How would the following query look if I was using the extension method syntax?

var query = from c in checks
group c by string.Format("{0} - {1}", c.CustomerId, c.CustomerName) 
into customerGroups
select new { Customer = customerGroups.Key, Payments = customerGroups }
like image 347
Dane O'Connor Avatar asked Jun 08 '09 21:06

Dane O'Connor


People also ask

How do you do GroupBy in LINQ?

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.

What does LINQ GroupBy return?

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()

Does LINQ GroupBy preserve order?

Found answer on MSDN: Yes.

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

It would look like this:

var query = checks
    .GroupBy(c => string.Format("{0} - {1}", c.CustomerId, c.CustomerName))
    .Select (g => new { Customer = g.Key, Payments = g });
like image 174
mqp Avatar answered Oct 14 '22 23:10

mqp