本文介绍了net 2.0中不同类型的结构的排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道如何对具有不同类型的结构列表进行排序(下面的示例代码)吗?
Does anyone know how to sort a list of struct with different types (sample code below)?
我们当前正在使用Net 2.0,因此我们无法使用Linq.
We are currently using Net 2.0, so we cannot use 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>
.
Or write a custom comparer (IComparer<dataKeys>
), or have dataKeys
implement IComparable<dataKeys>
.
这篇关于net 2.0中不同类型的结构的排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!