유형에 IComparer
을 구현하는 클래스의 인스턴스를 사용할 수 있습니다. 비교 자 구현은 적용 할 규칙을 알고 있습니다 (예 : 유형에 사전이있는 경우).
다음은 시작하기위한 구현 예입니다. Null 값을 가진 모든 다른 엣지 케이스를 구현하는 데 신경 쓰지 않았다는 점에 유의하십시오. 그것은 독자를위한 운동으로 남아 있습니다.
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.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();
그래서 사전에 무엇 :
는이 테스트 장비를 사용하여 위의 코드를 테스트하려면? 이름, 유형, 날짜 값이있는 키는 맞습니까? – rene@rene : 예. 너는 맞다. 모든 XML 노드를 키로서 그 노드 내부의 모든 값을 값으로 사용합니다. 날짜 = 2015-01-02 등 .... – user2645738