2013-07-01 60 views
0

這是我的代碼:C# - 無法在數組中比較兩個元素

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'值直接放入枚舉中。 –

+1

爲什麼不用Linq的'OrderBy'? –

+0

要在列表上做'排序',每次你有兩個元素從列表中,算法必須能夠確定哪一個比另一個大。這要求(兩個中的一個)對象實現「IComparable」,「IComparable 」或類似的。您使用匿名類型,因爲使用'new {Date = xxx}'。雖然匿名類型重寫'Equals'和'GetHashCode',但它們不實現'IComparable'或類似的。所以你可以說,如果匿名類型的兩個實例是平等的,但是你不能判斷一個是否「大於」另一個! –

回答

4

不用創建匿名類型,在你的情況下,結果distinctDateValues匿名類型的列表,而不是一個的DateTime列表,你應該得到的DateTime像下面OrderBy排序列表:

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

此外,你應該使用,而不是使用一個步驟與DateTime.Parse

2

只是猜測這裏...你distinctDateValues不千牛內置方法Field<DateTime>流如何自己比較......你需要實現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();