1

有没有一种简单的方法可以在列表中找到重复项,然后按出现次数对它们进行排序?此外,应删除重复项。

例如。你有一个List<String>这样的:

List<String> = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};

问题是,如何将此列表转换为 -> “6”、“1”、“2”、“4”、“5”?

4

6 回答 6

2

我认为最简单的方法是使用 LINQ 方法Distinct()

var originalList = …;
vat withoutDuplicates = originalList.Distinct();

尽管您应该注意,结果的顺序Distinct()是明确未记录的。

于 2012-09-11T14:28:22.697 回答
2

采用Linq.Distinct()

List<String> list = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
list = list.Distinct().ToList();
于 2012-09-11T14:29:46.910 回答
2

如果您实际上希望它们从最常见到最少排序-与您的示例不同-

var ordered = list
    .GroupBy(i => i)
    .OrderByDescending(g => g.Count())
    .Select(g => g.Key);

应该实现这一点。

于 2012-09-11T14:34:15.567 回答
0
Using System.Linq;
// Assuming inputList was the original string list
List<String> deDuped = inputList.Distinct().ToList();
于 2012-09-11T14:31:40.950 回答
0

由于不清楚您的确切含义,因此这里有两种可能含义的解决方案:

  1. 获取按出现次数排序的唯一列表

    对列表进行分组并按以下方式排序Count()

    List<String> list = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
    
    var q = from s in list
    group s by s into g
    orderby g.Count() descending
    select g.Key;
    
  2. 获取按列表中第一次出现的项目排序的唯一列表

    已经有几个使用建议Distinct,但是文档不保证它们按照它们在列表中出现的顺序出现(当前的Enumerable实现恰好以这种方式对它们进行排序,但对于其他提供者则不能保证):

    备注
    结果序列是无序的。

    为了保证顺序,添加一个 OrderBy 子句:

    var q = list.Distinct().OrderBy(s => list.IndexOf(s));
    
于 2012-09-11T14:36:40.610 回答
0

还不是最干净的,但这提供了正确的结果。

var originalData = new List<string>{"6","1","2","2","4","6","5","1","6","6","2"};
var result = new List<string>();

foreach (var myString in originalData)
{
    if (!result.Exists(s => s == myString))
        result.Add(myString);
}
于 2012-09-11T14:50:19.170 回答