タイプにIComparer
を実装するクラスのインスタンスを使用できます。次に、comparerの実装では、適用するルールがわかります。たとえば、タイプに辞書がある場合などです。
ここでは、開始するための実装例を示します。ヌル値ですべての異なるエッジケースを実装するのは面倒ではなかったことに注意してください。それは読者のための練習として残されています。
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