有谁知道如何对不同类型的struct列表进行排序(下面的示例代码)?
我们目前正在使用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
答案 0 :(得分:3)
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>
。
答案 1 :(得分:1)
是的,使用.Sort和自定义比较委托:
http://msdn.microsoft.com/en-us/library/w56d4y5z%28v=VS.80%29.aspx