Lukas Morkunas Lukas Morkunas - 3 months ago 50
C# Question

max amount of same item in a list with C#

Let's say I have this list:

1
1
1
1
2
2
2
3

I want to narrow it down with C# to a list with a maximum of two same items in a list so it would look like this:

1
1
2
2
3

I used to use 'distinct' like this:

string[] array = System.IO.File.ReadAllLines(@"C:\list.txt");
List<string> list = new List<string>(array);
List<string> distinct = list.Distinct().ToList();


but don't have an idea on how it could bring a max number of same values

Answer

You could do it with Linq as follows.

var Groups = Input.GroupBy( i => i );
var Result = Groups.SelectMany( iGroup => iGroup.Take(2) ).ToArray();
Comments