【问题标题】:List minimum with skip列表最小值与跳过
【发布时间】:2016-04-04 14:29:46
【问题描述】:

我收到此错误

至少一个对象必须实现 IComparable。

从此代码

namespace S
{
    public sealed class C
    {
    public class Set
    {
        public DateTime time { get; set; }
        public Decimal x { get; set; }
        public Decimal y { get; set; }
    }

    public static Dictionary<String, List<Set>> _SET;

    public static void MyFunction()
    {
        Int32 _h = 1, _period = 30;
        Decimal _my_decimal = (_SET[" my key "].Skip(_h * _period).Take(_period).Min().x);//Error is at this line!
    }
}

}

我只是想在某个数字之后获得最小值。我该怎么做?

【问题讨论】:

    标签: c# linq list ienumerable


    【解决方案1】:

    要在 List&lt;Set&gt; 上使用 Min(),您需要做以下两件事之一:

    • 元素的类型 (Set) 必须实现 IComparable 接口或
    • 您需要提供一个 lambda,用于选择比较元素的值。

    所以如果你想要最小的x,你可以这样做:

    Decimal _my_decimal = (_SET[" my key "].Skip(_h * _period).
              Take(_period).Min(s => s.x).x);
    

    如果您想要确定最小值的方法更复杂,您可以在Set 类中实现IComparable 接口,如下所示:

    public class Set : IComparable
    {
        public DateTime time { get; set; }
        public Decimal x { get; set; }
        public Decimal y { get; set; }
        public int CompareTo(object obj)
        {
            Set other = obj as Set;
            return other == null ? 1 : x.CompareTo(other.x);
        }
    }
    

    该示例再次显示了x 的比较,但您也可以进行更复杂的比较。

    【讨论】:

      【解决方案2】:

      此代码的最大问题是您试图获取 Min() 值,但使用未实现 IComparable 的对象列表。

      在这种情况下,您可以在 Set 类上实现 IComparable 接口或获取 Min 选择应返回的属性:

      命名空间 S { 公共密封C级 { 公共课集 { 公共日期时间时间 { 获取;放; } 公共十进制 x { 得到;放; } 公共十进制 y { 得到;放; } } 公共静态词典> _SET; 公共静态无效 MyFunction() { Int32 _h = 1,_period = 30; 十进制 _my_decimal = (_SET["我的密钥"].Skip(_h * _period).Take(_period).Min(y => y.x); } }

      【讨论】:

      • 谢谢,我觉得你的回答没有上面... y.x).x 的bug。
      【解决方案3】:

      正如错误所说,您需要实现 IComparable 接口才能获取Min 值。

      查询不知道它应该使用什么来确定对象应该进入的顺序。

      看看here如何实现接口。

      如果您按日期进行比较,您的班级 Set 将如下所示:

      public class Set : IComparable
      {
          public DateTime time { get; set; }
          public Decimal x { get; set; }
          public Decimal y { get; set; }
      
          public int CompareTo(object obj) 
          {
                 if (obj == null) return 1;
      
                 Set s = obj as Set;
                 if (s != null) 
                     return this.time.CompareTo(s.time);
                 else
                    throw new ArgumentException("Object is not a Set");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-13
        • 2012-10-14
        • 2015-03-13
        • 2020-06-06
        • 2013-04-08
        • 1970-01-01
        • 2016-09-04
        • 2013-12-27
        相关资源
        最近更新 更多