VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/linq-grouping-operator-groupby/

⇱ LINQ | Grouping Operator | GroupBy - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

LINQ | Grouping Operator | GroupBy

Last Updated : 26 May, 2019
In LINQ, grouping operators pick the elements of the sequence or collection which contains common attributes and serve them in a group. Or in other words, we can say that the grouping operator returns the group of elements based on the given key. This group is held in a special type of collection, which implements the IGrouping<TKey, TElement> interface, where TKey is the key through which the group is created and TElement is the collection of elements which peers with the grouping key value. For example, a sequence contains 6 elements, i.e, Abc, cvd, Abc, Abc, ert, Por,. Now we want a group which contains all the Abc present in that sequence. So Abc is the key through which we create another group that contains 3 Abc. As shown in the below image: 👁 Image
The Standard Query Operator contains 2 different types of grouping operators:
  1. GroupBy
  2. ToLookup

GroupBy Operator

The working of the GroupBy operator is similar to the SQL GroupBy clause. It is used to return the group of elements which share the common attributes or key from the given sequence or collection. Every group is represented by IGrouping<TKey, TElement> object. Important Points:
  • It support query syntax in both C# and VB.Net languages. As shown in example 1.
  • You can also use into with GroupBy in C# query. The into keyword allows you to continue with the query and can perform more query operation. Or in other words, it is a temporary identifier which allows you to perform additional query operation.
  • 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. As shown in example 2.
  • It present in both the Queryable and Enumerable class. And in these classes, the GroupBy method is overloaded in eight different types.
  • It is implemented by using deferred execution.
  • Key value can be of any type either string, int, float, anonymous, bool, etc. depends upon the requirement of the user.
  • The group return by this operator can contain zero or more elements that match the key value.
Example 1:
Output:
Group By Salary: 20000
Employee Name: Anjita
Group By Salary: 30000
Employee Name: Soniya
Group By Salary: 40000
Employee Name: Rohit
Employee Name: Supriya
Employee Name: Anil
Group By Salary: 50000
Employee Name: Anju
Example 2:
Output:
Group By Language: Ruby
Employee Name: Anjita
Group By Language: Java
Employee Name: Soniya
Employee Name: Supriya
Group By Language: Perl
Employee Name: Rohit
Group By Language: C#
Employee Name: Anil
Employee Name: Anju
Comment
Article Tags:
Article Tags:

Explore