LINQ在List< List< string>>中获得唯一计数/排序. [英] LINQ to get Distinct Count/Sort in List<List<string>>

查看:60
本文介绍了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

这篇关于LINQ在List&lt; List&lt; string&gt;&gt;中获得唯一计数/排序.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆