GroupBy() Method in C#


The GroupBy() is an extension method that returns a group of elements from the given collection based on some key value.

The following is our array −

int[] arr = { 2, 30, 45, 60, 70 };

Now, we will use GroupBy() to group the elements smaller than 50 −

arr.GroupBy(b => chkSmaller(b));

The above chkSmaller() finds the elements smaller than 50.

Let us see the complete code −

Example

 Live Demo

using System;
using System.Linq;

class Demo {
   static void Main() {
      int[] arr = { 2, 30, 45, 60, 70 };
      var check = arr.GroupBy(b => chkSmaller(b));

      foreach (var val in check) {
         Console.WriteLine(val.Key);
         foreach (var res in val) {
            Console.WriteLine(res);
         }
      }
   }
   static bool chkSmaller(int a) {
      return a <= 50;
   }
}

Output

True
2
30
45
False
60
70

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements