-1

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

Lukas Morkunas
  • 316
  • 3
  • 12
  • 8
    Great idea. What did you try so far? – Khalil Khalaf Aug 09 '16 at 12:44
  • 6
    I agree with everything above except the great idea bit – Liam Aug 09 '16 at 12:44
  • well I tried this: string[] array = System.IO.File.ReadAllLines(@"C:\list.txt"); List list = new List(array); List distinct = list.Distinct().ToList(); but obviously it only brings up distinct items – Lukas Morkunas Aug 09 '16 at 12:45
  • 1
    @LukasMorkunas You should edit the question to include that code instead of putting it into a comment. – juharr Aug 09 '16 at 12:46
  • 1
    No no no, put your substantive info in your *question*, not in the comments! – rory.ap Aug 09 '16 at 12:46
  • So why didn't you include this in the question. Your question is not clear pleas read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) Even including that code it's not clear what you actually want – Liam Aug 09 '16 at 12:46
  • Is it already in order? – CodyMR Aug 09 '16 at 12:47
  • Is each number on a separate line or are they separated by spaces? – juharr Aug 09 '16 at 12:48
  • Look into LINQ extension methods `GroupBy`, `Count`, `OrderByDescending`, and `First`. This should give you the toolbox required to solve the problem. – Baldrick Aug 09 '16 at 12:48
  • This should be helpful [**What is C# equivalent of in C++?**](http://stackoverflow.com/questions/21183414/what-is-c-sharp-equivalent-of-map-in-c) where each unique item is the key and its count is the value – Khalil Khalaf Aug 09 '16 at 12:48

1 Answers1

8

You could do it with Linq as follows.

var Groups = Input.GroupBy( i => i );
var Result = Groups.SelectMany( iGroup => iGroup.Take(2) ).ToArray();
Codor
  • 17,447
  • 9
  • 29
  • 56