简体   繁体   English

C#-无法比较数组中的两个元素

[英]C# - Failed to compare two elements in the array

This is my code: 这是我的代码:

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

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

Values in distinctDateValues are: differentDateValues中的值是:

在此处输入图片说明

The error i am getting is "Failed to compare two elements in the array." 我得到的错误是“无法比较数组中的两个元素”。

Can anybody suggest me as what i am doing wrong here. 有人可以建议我,因为我在这里做错了。 I want to sort the values in date column of distinctDateValues. 我想对distinctDateValues的日期列中的值进行排序。

Needless to create anonymous type, in your case the result distinctDateValues is a list of anonymous type , not a list of DateTime , you should get the sorted list of DateTime like below with OrderBy : 无需创建匿名类型,在您的情况下,结果distinctDateValues匿名类型的列表,而不是DateTime的列表,您应该使用OrderBy像下面那样获得DateTime的排序列表:

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

Also, you should use built-in method Field<DateTime> instead of using one more step with DateTime.Parse 此外,应使用内置的方法Field<DateTime>而不是使用与一个多步骤DateTime.Parse

Just guessing here... your distinctDateValues don't know how to compare themselves... You would need to implement IComparable or something... 只是在这里猜测...您的distinctDateValues不知道如何比较自己...您将需要实现IComparable东西。

Try this: 尝试这个:

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

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

If you really want to create an anonymous type (eg, you are only showing us a small part of your code), try this: 如果您确实要创建匿名类型(例如,您仅向我们展示了代码的一小部分),请尝试以下操作:

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();

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

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