這個問題在這里已經有了答案: 如何按物件中的屬性對 List<T> 進行排序 22 個回答 7 小時前關閉。
我正在嘗試使用 對物件陣列進行排序Array.Sort,但得到一個 InvalidOperationException。正如我所讀到的,我正在嘗試對一個復雜的物件進行排序,我需要使用比較IComparable <T>介面,但我不明白它是如何作業的。
有我的代碼:
public class C
{
public int I { get; set; }
}
static void Main(string[] args)
{
C[] classes = new C[100000];
Random rand = new Random();
for (int i = 0; i < 100000; i )
{
classes[i] = new C { I = rand.Next(1, 100000) };
}
Array.Sort<C>(classes); // Here I get an exception
}
uj5u.com熱心網友回復:
您應該向 .Net 解釋如何比較類:
...
// having a and b instances we should compare I properties
Array.Sort<C>(classes, (a, b) => a.I.CompareTo(b.I));
...
或者你可以進行class C 比較(為了Array.Sort<C>(classes);開始作業):
public class C : IComparable<C> {
public int I { get; set; }
public int CompareTo(C other) {
if (null == other)
return 1;
return I.CompareTo(other.I);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383208.html
