使用 LINQ 获取前 n 个值,包括重复项

问题描述 投票:0回答:2

请考虑这个列表:

City            Value
---------------------
City1             10
City2             20
City3             30
City4             40
City5             50
City6             60

如果我想获得城市中的前 3 名价值,我可以写这个

LINQ

MyList.OrderByDescending(o=>o.Value).Take(3);

现在考虑这个列表:

City            Value
---------------------
City1             10
City2             20
City3             30
City4             40
City5             50
City6             60
City7             60

我想要一个查询,返回所有具有最高 3 最高值的城市。对于上面的列表,我想要这个结果:

City            Value
---------------------
City7             60
City6             60
City5             50
City4             40

谢谢

c# linq linq-to-entities c#-7.0
2个回答
10
投票
var result = MyList.GroupBy(o => o.Value)
                   .OrderByDescending(g => g.Key)
                   .Take(3)
                   .SelectMany(g => g)
                   .ToList();

此列表将包含具有前 3 个最高值的所有城市,按值降序排列。


0
投票

有点笨拙,这个解决方案找到第三高的 DISTINCT 值,然后返回所有等于或大于它的值。

using System.Diagnostics.CodeAnalysis;

var MyList = new List<(string, string)>();
MyList.Add(("City1", "10"));
MyList.Add(("City2", "20"));
MyList.Add(("City3", "30"));
MyList.Add(("City4", "40"));
MyList.Add(("City5", "50"));
MyList.Add(("City6", "60"));
MyList.Add(("City7", "60"));
var topThreeDistinct = MyList.Distinct(new StringStringComparer()).OrderByDescending(o => o.Item2).Take(3).ToList();

var thirdValue = topThreeDistinct[2].Item2;
Console.WriteLine($"Third value = {thirdValue}");

var topThreeAll = MyList.Where(o => o.Item2.CompareTo(thirdValue) >= 0 ).ToList();
foreach (var item in topThreeAll)
    Console.WriteLine(item);
Console.WriteLine("FINISHED");

class StringStringComparer : IEqualityComparer<(string, string)>
{
    public bool Equals((string, string) x, (string, string) y)
    {
        if (x.Item2 == y.Item2)
        {
            return true;
        }
        else
        {
            return false;
        };
    }

    public int GetHashCode([DisallowNull] (string, string) obj)
    {
        return Convert.ToInt32(obj.Item2);
    }
}

(C# .NET 6.0 控制台应用程序)

© www.soinside.com 2019 - 2024. All rights reserved.