Group by Operator in C#

CsharpProgrammingServer Side Programming

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
raja
Published on 05-Sep-2018 10:37:51
Advertisements