How to Get the Top 5 elements from a List in C# ?
If you want to get the top 5 elements from a list in C# or skip the first item and get the next five elements from a List , you can use the Take and the Skip methods.
How to Get the Top 5 elements from a List in C# ?
Below is a sample code snippet demonstrating the usage of the Skip and Take extension methods.
C#
x
33
33
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
5
namespace ACCode
6
{
7
class Program
8
{
9
static void Main(string[] args)
10
{
11
List<string> LstMovies = new List<string>();
12
LstMovies.Add("1");
13
LstMovies.Add("2");
14
LstMovies.Add("3");
15
LstMovies.Add("4");
16
LstMovies.Add("5");
17
LstMovies.Add("6");
18
// Take Top 5 elements from the List
19
var Top5Items = LstMovies.Take(5);
20
foreach(var item in Top5Items)
21
Console.WriteLine(item);
22
23
Console.WriteLine("-----------------------------------");
24
// Skip the First item and take the 5 items
25
var SkipFirstFiveItems = LstMovies.Skip(1).Take(5);
26
foreach (var item in SkipFirstFiveItems)
27
Console.WriteLine(item);
28
Console.ReadLine();
29
}
30
31
}
32
33
}
Leave Your Comment