C# - Failed to compare two elements in the array
Solution 1
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
Solution 2
Just guessing here... your distinctDateValues
don't know how to compare themselves... You would need to implement IComparable
or something...
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 (e.g., 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();
user1254053
Updated on June 27, 2022Comments
-
user1254053 almost 2 years
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:
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.