![](/img/trans.png)
[英]List<> of objects, different types, sort and pull out types individually?
[英]sort list of struct of different types in net 2.0
有誰知道如何對不同類型的結構列表進行排序(下面的示例代碼)?
我們目前正在使用Net 2.0,因此我們無法使用Linq。
提前致謝!
public struct dataKeys
{
private long key1;
private long key2;
private string key3;
public long Key1;
{
get { return key1;}
set { key1 = value; }
}
public long Key2;
{
get { return key2;}
set { key2 = value; }
}
public string Key3;
{
get { return key3;}
set { key3 = value; }
}
}
. . .
List<dataKeys> dataKeyList = new List<dataKeys>();
// tried this but will only work for one
// dataKeyList.Sort((s1, s2) => s1.Key1.CompareTo(s2.Key1));
就像是:
FROM:
2, 2, C
1, 1, A
1, 3, A
3, 1, B
1, 2, B
2, 1, A
2, 3, A
1, 2, A
TO:
1, 1, A
1, 2, A
1, 2, B
1, 3, A
2, 1, A
2, 2, C
2, 3, A
3, 1, B
dataKeyList.Sort((s1, s2) => {
int result = s1.Key1.CompareTo(s2.Key1);
if(result == 0) {
result = s1.Key2.CompareTo(s2.Key2);
if(result == 0) {
result = s1.Key3.CompareTo(s2.Key3);
}
}
return result;
});
或者編寫自定義比較器( IComparer<dataKeys>
),或者讓dataKeys
實現IComparable<dataKeys>
。
是的,使用.Sort與自定義比較委托:
http://msdn.microsoft.com/en-us/library/w56d4y5z%28v=VS.80%29.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.