Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Failed to compare two elements in the array

Tags:

c#

linq

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:

enter image description here

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.

like image 423
user1254053 Avatar asked Oct 20 '25 04:10

user1254053


1 Answers

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:

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

like image 195
cuongle Avatar answered Oct 21 '25 18:10

cuongle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!