C#列表中相同项目的最大数量

Luk*_*nas -1 c# arrays sorting list max

假设我有这个清单:

1 1 1 1 2 2 2 3

我想用C#将其缩小到一个列表中,列表中最多有两个相同的项目,所以它看起来像这样:

1 1 2 2 3

我曾经像这样使用'distinct':

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

但是不知道如何才能带来最大数量的相同值

Cod*_*dor 8

您可以使用Linq执行以下操作.

var Groups = Input.GroupBy( i => i );
var Result = Groups.SelectMany( iGroup => iGroup.Take(2) ).ToArray();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我带了几次尝试来弥补它! (2认同)