C# - 数组中两个元素比较失败。

3
这是我的代码:
 var distinctDateValues = dt.AsEnumerable()
                   .Select(row => new
                   {
                       Date = DateTime.Parse(row.Field<string>("DAY"))
                   })
                   .Distinct()
                   .ToList();

 distinctDateValues.Sort(); // getting error on this line

distinctDateValues中的值为:

enter image description here

我收到的错误是“无法比较数组中的两个元素。”

有人能告诉我在这里做错了什么吗?我想对distinctDateValues中的日期列进行排序。


1
你真的需要一个只有一个字段(“日期”)的匿名对象的枚举吗?你可以直接将DateTime值放入你的枚举中。 - O. R. Mapper
1
为什么不使用Linq的OrderBy - Grant Thomas
对于 List<Something> 的排序,每次比较两个元素时,算法必须能够确定哪一个大于另一个。这要求其中一个对象实现 IComparableIComparable<Something> 或类似接口。您可以使用匿名类型,例如 new { Date = xxx }。虽然匿名类型重写了 EqualsGetHashCode 方法,但它们并没有实现 IComparable 或类似接口。因此,您可以判断两个匿名类型的实例是否相等,但无法确定一个实例是否“大于”另一个实例! - Jeppe Stig Nielsen
2个回答

7

在你的情况下,不需要创建匿名类型,因为结果distinctDateValues是一个匿名类型列表,而不是DateTime列表。你可以通过使用OrderBy来获取排序后的DateTime列表,如下所示:

var distinctDateValues = dt.AsEnumerable()
               .Select(row => row.Field<DateTime>("DAY"))
               .Distinct()
               .OrderBy(x => x)
               .ToList();

此外,您应该使用内置方法Field<DateTime>而不是使用DateTime.Parse进行额外的步骤。

3

我猜测...你的distinctDateValues不知道如何比较自己...你需要实现IComparable或其他方法...

尝试这样做:

var distinctDateValues = dt.AsEnumerable()
               .Select(row => DateTime.Parse(row.Field<string>("DAY")))
               .Distinct()
               .ToList();

 distinctDateValues.Sort(); // should not get any errors here...

如果您真的想创建一个匿名类型(例如,您只向我们展示了代码的一小部分),请尝试以下方法:

var distinctDateValues = dt.AsEnumerable()
               .Select(row => new
               {
                   Date = DateTime.Parse(row.Field<string>("DAY"))
               })    
               .Distinct()
               .OrderBy(d => d.Date) // do the sorting here with linq
               .ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接