我有一个List<>
包含 a List<string>
,我需要从 中确定唯一计数List<string
,并按计数频率排序。
例子:
这将输出(等级/组合/频率)
我可以想出一种蛮力方法,但可以用 LINQ 更优雅地完成吗?据我所知,这并不完全是笛卡尔方法。
谢谢。
您可以编写自己的文件IEqualityComparer
并将其与GroupBy
.
public class StringArrayValueComparer : IEqualityComparer<List<string>>
{
public bool Equals(List<string> x, List<string> y)
=> x.SequenceEqual(y);
public int GetHashCode(List<string> obj)
=> obj.Aggregate(1, (current, s) => current * 31 + s.GetHashCode());
}
var list = new List<List<string>>(new[]
{
new List<string>(new [] { "a", "b", "c" }),
new List<string>(new [] { "d", "e", "f" }),
new List<string>(new [] { "a", "b" }),
new List<string>(new [] { "a", "b", "c" }),
new List<string>(new [] { "a", "b", "c" }),
new List<string>(new [] { "a", "b" })
});
var orderedList = list
.GroupBy(x => x, x => x, (x, enumerable) => new { Key = x, Count = enumerable.Count()}, new StringArrayValueComparer())
.OrderByDescending(x => x.Count)
.Select((x, index) => new { Rank = index + 1, Combination = x.Key, Frequency = x.Count });
foreach (var entry in orderedList)
{
Console.WriteLine($"{entry.Rank} - {string.Join(",", entry.Combination)} - {entry.Frequency}");
}
1 - a,b,c - 3
2 - a,b - 2
3 - d,e,f - 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句