C# Program to return specified number of elements from the beginning of a sequence

CsharpProgrammingServer Side Programming

<p>Set an array and arrange it in descending order using OrderByDescending.</p><pre class="result notranslate">int[] prod = { 290, 340, 129, 540, 456, 898, 765, 789, 345};</pre><p>Now, use the Take() method to return specified number of elements from the beginning.</p><pre class="result notranslate">Enumerable&lt;int&gt; units = prod.AsQueryable().OrderByDescending(s =&gt; s).Take(2);</pre><p>Let us see the complete code.</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/PuTjtT" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">using System; using System.Linq; using System.Collections.Generic; public class Demo { &nbsp; &nbsp;public static void Main() { &nbsp; &nbsp; &nbsp; int[] prod = { 290, 340, 129, 540, 456, 898, 765, 789, 345}; &nbsp; &nbsp; &nbsp; // Volume of top two products &nbsp; &nbsp; &nbsp; IEnumerable&lt;int&gt; units = prod.AsQueryable().OrderByDescending(s =&gt; s).Take(2); &nbsp; &nbsp; &nbsp; foreach (int res in units) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(res); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">898 789</pre>
raja
Updated on 23-Jun-2020 09:10:41

Advertisements