您可以使用为您的类型实现IComparer 的类的实例。然后比较器实现知道要应用哪些规则,例如当您的类型有字典时。
这是一个示例实现,可帮助您入门。请注意,我没有费心用空值实现所有不同的边缘情况。这留给读者作为练习。
public class Test
{
public int ID{get;set;}
public int Name{get;set;}
public int Type{get;set;}
public Dictionary<string,string> XML{get;set;}
// this class handles comparing a type that has a dictionary of strings
private class Comparer: IComparer<Test>
{
string _key;
// key is the keyvalue from the dictionary we want to compare against
public Comparer(string key)
{
_key=key;
}
public int Compare(Test left, Test right)
{
// let's ignore the null cases,
if (left == null && right == null) return 0;
string leftValue;
string rightValue;
// if both Dictionaries have the key we want to sort on ...
if (left.XML.TryGetValue(_key, out leftValue) &&
right.XML.TryGetValue(_key, out rightValue))
{
// ... lets compare on those values
return leftValue.CompareTo(rightValue);
}
return 0;
}
}
// this method gives you an Instace that implements an IComparer
// that knows how to handle your type with its dictionary
public static IComparer<Test> SortOn(string key)
{
return new Comparer(key);
}
}
在任何采用 IComparer 的 Sort 方法中使用上述类,例如,在您可以执行的普通 List 上:
list.Sort(Test.SortOn("Date"));
这将对列表进行排序。
要测试上述代码,您可以使用此测试台:
var list = new List<Test> {
new Test {ID=1, Name =2, Type=3,
XML = new Dictionary<string,string>{{"Date","2017-09-01"}}},
new Test {ID=10, Name =20, Type=30,
XML = new Dictionary<string,string>{{"Date","2017-01-01"}}},
new Test {ID=100, Name =200, Type=300,
XML = new Dictionary<string,string>{{"Date","2017-03-01"}}},
};
list.Sort(Test.SortOn("Date"));
list.Dump();