Group by Operator in C#

CsharpProgrammingServer Side Programming

<p>Use the group by the operator in C# to separate the results of an expression into parts.</p><p>Let&rsquo;s say the following is our array &minus;</p><pre class="result notranslate">int[] a = { 5, 10, 15, 20, 25, 30 };</pre><p>Now, using Group by and orderby, we will find the elements greater than 20 &minus;</p><pre class="result notranslate">var check = from element in a orderby element group element by chkGreater(element);</pre><p>The following is the complete code &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/b4KbPk" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">using System; using System.Linq; class Demo { &nbsp; &nbsp;static void Main() { &nbsp; &nbsp; &nbsp; int[] a = { 5, 10, 15, 20, 25, 30 }; &nbsp; &nbsp; &nbsp; var check = from element in a orderby element group element by chkGreater(element); &nbsp; &nbsp; &nbsp; foreach (var val in check) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(val.Key); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;foreach (var res in val) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(res); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;static bool chkGreater(int a) { &nbsp; &nbsp; &nbsp; return a &gt;= 20; &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">False 5 10 15 True 20 25 30</pre>
raja
Updated on 22-Jun-2020 14:51:03

Advertisements