Group by Operator in C#


Use the group by the operator in C# to separate the results of an expression into parts.

Let’s say the following is our array −

int[] a = { 5, 10, 15, 20, 25, 30 };

Now, using Group by and orderby, we will find the elements greater than 20 −

var check = from element in a orderby element group element by chkGreater(element);

The following is the complete code −

Example

 Live Demo

using System;
using System.Linq;
class Demo {
   static void Main() {
      int[] a = { 5, 10, 15, 20, 25, 30 };
      var check = from element in a orderby element group element by chkGreater(element);
      foreach (var val in check) {
         Console.WriteLine(val.Key);
         foreach (var res in val) {
            Console.WriteLine(res);
         }
      }
   }
   static bool chkGreater(int a) {
      return a >= 20;
   }
}

Output

False
5
10
15
True
20
25
30

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements