GroupBy() Method in C#

CsharpProgrammingServer Side Programming

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
raja
Published on 04-Sep-2018 11:32:11
Advertisements