LINQ to get Distinct Count/Sort in List<List<string>>

ε祈祈猫儿з 提交于 2019-12-07 19:24:30
NtFreX

You could write your own IEqualityComparer and use it with 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!