我收到此错误
至少有一个对象必须实现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!
}
}
}
我只想在一定数量后获得最小值。我该怎么做?
答案 0 :(得分:1)
要在Min()
上使用List<Set>
,您需要执行以下两项操作之一:
Set
)必须实现IComparable
接口或因此,如果您想要最低x
,您可以这样做:
Decimal _my_decimal = (_SET[" my key "].Skip(_h * _period).
Take(_period).Min(s => s.x).x);
如果您希望确定最小值的方式更复杂,则可以在IComparable
类中实现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)
{
Set other = obj as Set;
return other == null ? 1 : x.CompareTo(other.x);
}
}
该示例仅显示x
的比较,但您也可以进行更复杂的比较。
答案 1 :(得分:1)
这段代码的一个大问题是你试图得到Min()
值,但是有一个没有实现IComparable的对象列表。
在这种情况下,您可以在Set
类上实现IComparable接口,或者让Min
选择应返回的属性:
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> _SET; public static void MyFunction() { Int32 _h = 1, _period = 30; Decimal _my_decimal = (_SET[" my key "].Skip(_h * _period).Take(_period).Min(y => y.x); } }
答案 2 :(得分:1)
如错误所示,您需要实现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");
}
}