是否有一种简单的方法可以在列表中找到重复项,然后按外观数量对它们进行排序?此外,应删除重复项。
EG。你有这样的List<String>
:
List<String> = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
问题是,如何将此列表转换为 - &gt; “6”,“1”,“2”,“4”,“5”?
答案 0 :(得分:2)
我认为最简单的方法是使用LINQ方法Distinct()
:
var originalList = …;
vat withoutDuplicates = originalList.Distinct();
虽然您应该注意Distinct()
的结果顺序明确没有记录。
答案 1 :(得分:2)
使用Linq.Distinct()
List<String> list = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
list = list.Distinct().ToList();
答案 2 :(得分:2)
如果你真的希望从最常见到最少订购它们 - 不像你的例子那样 -
var ordered = list
.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Select(g => g.Key);
应该实现这一点。
答案 3 :(得分:0)
Using System.Linq;
// Assuming inputList was the original string list
List<String> deDuped = inputList.Distinct().ToList();
答案 4 :(得分:0)
由于目前尚不清楚你的意思,这里有两种可能含义的解决方案:
获取按出现次数排序的唯一列表:
将列表分组并按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;
获取按列表中第一次出现的项目排序的唯一列表
已经有一些使用Distinct
的建议,但是documentation并不保证它们按照它们在列表中出现的顺序出现(当前Enumerable
实现恰好对它们进行排序这样,但对于其他供应商,它不能保证):
<强>说明强>
结果序列是无序的。
为了保证订单,请添加OrderBy子句:
var q = list.Distinct().OrderBy(s => list.IndexOf(s));
答案 5 :(得分: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);
}