简体   繁体   English

根据最高价值从列表中获取前5名

[英]Grab top 5 from a list based on highest value

I have a list which is made up of two items postcode and totalCost. 我有一个列表,该列表由两项邮政编码和totalCost组成。 I want to grab the top 5 items from this list which have the highest total cost. 我想从此列表中获取总费用最高的前5个项目。 I have tried 我努力了

var top5 = list.Take(5).OrderByDescending(a => a.TotalCost);

also

var top5 = list.OrderByDescending(a=> a.TotalCost).Take(5);

Neither of these queries produce anything in var called top5. 这些查询都不会在var中产生任何东西,称为top5。 What is wrong with this syntax please? 请问这种语法有什么问题?

 var i = sums.OrderByDescending(x => x.TotalCost).Take(5).ToList();

    foreach (var postCodeSum in i)
    {
        Console.WriteLine(postCodeSum.TotalCost);
    }

EDIT: Didn't realise you wanted the highest values, edited the code; 编辑:没意识到你想要最高的价值,编辑了代码; I've ran the code and it should work just fine. 我已经运行了代码,它应该可以正常工作。

LINQ can be used : LINQ可以使用:

.OrderByDescending(x => x.TotalCost).Take(5).ToList();

The problem is the .ToList() you forgot. 问题是您忘记了.ToList()。

The supplied query( OrderByDescending followed by Take() )should work, make sure that the property/fileds in the class are public. 提供的查询( OrderByDescending后跟Take() )应该起作用,请确保该类中的属性/文件是公共的。 I'm answering based on the comment 我根据评论回答

The PostCodeSum class only contains private decimal _totalCost; PostCodeSum类仅包含私有小数_totalCost; private string _postCode; 私有字符串_postCode; – Giraffe 4 m –长颈鹿4 m

If it is private as you mentioned you will definitely get compilation error at a.TotalCost in the query. 如果您提到它是私有的,则肯定会在查询中的a.TotalCost处收到编译错误。 if the properties are accessible means the following code will work: 如果属性是可访问的,则以下代码将起作用:

var top5 = postCodeSumTotals.OrderByDescending(a => a.TotalCost).Take(5); 

Take a look at this Working Example 看一下这个工作示例

Resolved it by putting the result into a list instead. 通过将结果放入列表来解决它。 Not sure why the other way didn't work. 不知道为什么其他方式不起作用。

List<PostCodeSum> postCodeSumTotalsFinal = postCodeSumTotals.OrderByDescending(o => o.TotalCost).Take(5).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM