Lukas Morkunas Lukas Morkunas - 4 months ago 11
C# Question

How to narrow list down to a max number of same items in C#

Let's say I have this list in an array called 'array':

[0]a.1
[1]b.1
[2]c.1
[3]d.1
[4]e.2
[5]f.2
[6]g.2
[7]h.3


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

[0]a.1
[1]b.1
[2]e.2
[3]f.2
[4]h.3


I was trying to use 'GroupBy':

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


but I'm not sure how to only take what's after the dot into consideration and not the whole item

Answer

I'm not sure how to only take what's after the dot into consideration and not the whole item

If the dot is guaranteed to be present, split on the dot, and take the second item:

var Groups = array.GroupBy(i => i.Split('.')[1]);

The rest of your code, with SelectMany and Take(2), is correct.