使用Linq .Min()-至少一个对象必须实现IComparable [英] Using Linq .Min() - At least one object must implement IComparable

查看:299
本文介绍了使用Linq .Min()-至少一个对象必须实现IComparable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个集合中的最小值,而我正在使用LINQ来做到这一点.我已经在线阅读了可以使用Min()的信息,但是却收到了错误消息:

I want to get the smallest value in a collection and I am using LINQ to do this. I've read online I can use Min() but I am getting the error message:

 At least one object must implement IComparable

这是我的代码

public virtual void GetBestValue(ModelEnergyCalculator ModelEnergyCalculator)
{
     ModelTariffQuote ModelTariffQuote = (from q in ModelEnergyCalculator.ModelTariffQuotes   
                                                  select q).Min();                     
}

这是我的收藏集

    -       -       ModelEnergyCalculator   {EnergyHelpline.Model.ModelEnergyCalculator}    EnergyHelpline.Model.ModelEnergyCalculator
-       ModelTariffQuotes   Count = 4   System.Collections.Generic.List<EnergyHelpline.Model.ModelTariffQuote>
-       [0] {EnergyHelpline.Model.ModelTariffQuote} EnergyHelpline.Model.ModelTariffQuote
        ElectricityUsage    0   decimal
        FinalElectricityCost    179.97655091937073972602739726  decimal
        FinalGasCost    112.48534432460671232876712328  decimal
        GasUsage    0   decimal
        InitialElectricityCost  30.0117245403146958904109589    decimal
        InitialGasCost  18.757327837696684931506849312  decimal
+       QuoteIssuedDate {01/01/0001 00:00:00}   System.DateTime
        TariffName  null    string
        TotalCalculatedCost 341.23094762198883287671232875  decimal
+       [1] {EnergyHelpline.Model.ModelTariffQuote} EnergyHelpline.Model.ModelTariffQuote
+       [2] {EnergyHelpline.Model.ModelTariffQuote} EnergyHelpline.Model.ModelTariffQuote
+       [3] {EnergyHelpline.Model.ModelTariffQuote} EnergyHelpline.Model.ModelTariffQuote
+       Raw View        
+       ModelTariffs    Count = 4   System.Collections.Generic.List<EnergyHelpline.Model.ModelTariff>

如何解决此错误,或者是否有更好的方法来获取最小值?

How do I fix this error or is there a better way for getting the smallest value?

推荐答案

与使用IComparable相比,一种更简单,更灵活的方法是根据需要对对象进行排序并获取第一个对象.如果您需要最高的价格,则只需要使用OrderByDescending.

An easier and more flexible way of doing this than using IComparable is to order the objects as you need and take the first one. If you need the highest then you just need to use OrderByDescending.

var lowest = ModelEnergyCalculator.ModelTariffQuotes
    .OrderBy(m => m.GasFinalRate)
    .FirstOrDefault();

这篇关于使用Linq .Min()-至少一个对象必须实现IComparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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