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

旧巷老猫 提交于 2019-12-08 07:32:44

问题


I have a List<> that contains a List<string>, of which I need to determine the unique count from the List<string, and order by the frequency of the count.

Example:

  • "a","b","c"
  • "d","e","f"
  • "a","b"
  • "a", "b", "c"
  • "a", "b", "c"
  • "a","b"

This would output (rank / combination / frequency)

  • 1 - "a", "b", "c" - 3
  • 2 - "a", "b" - 2
  • 3 "d", "e", "f" - 1

I can come up with a brute-force approach but can this be done more elegantly with LINQ? This isn't exactly a Cartesian approach from what I can tell.

Thanks.


回答1:


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



来源:https://stackoverflow.com/questions/44737685/linq-to-get-distinct-count-sort-in-listliststring

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