LINQ在List< List< string>>中获得唯一计数/排序.

LINQ在List< List< string>>中获得唯一计数/排序.

问题描述:

我有一个包含List<string>List<>,我需要根据List<string确定唯一计数,并按计数频率进行排序.

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.

示例:

  • "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

我可以提出一种蛮力方法,但是使用LINQ可以更优雅地做到这一点吗?据我所知,这完全不是笛卡尔方法.

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.

谢谢.

您可以编写自己的IEqualityComparer并将其与GroupBy一起使用.

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

1 - a,b,c - 3

2-a,b-2

3-d,e,f-1

3 - d,e,f - 1