2017-11-27 3 views
0

私はこのソートデータテーブル

ID Name Type XML 
1 Test Pro <sample><Name>xyz</Name><Type>xyz</Type><Date>2015-01-01</Date></sample> 
2 Test2 Pro2 <sample><Name>abc</Name><Type>pqr</Type><Date>2015-01-02</Date></sample> 

のようなのDataTableを取得

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;) 
} 

以下のように私はこのXMLは、キーと値のペアとしてノードとその値が含まれているクラスにこれを変換します。今、私はユーザーの入力に基づいてこれを並べ替えるしたいと思います。例えばユーザーが日付またはタイプの名前でソートしたい場合。どうやってするか?データテーブルまたはリストに直接ソートすると機能します。

私はデータテーブルでソートしようとしましたが、常に結果は変わりません。同じことについて何か提案してください。

+0

だから辞書に何である:

は、この試験装置を使用することができます上記のコードをテストするには?名前、タイプ、日付、その値を持つキー、そうですか? – rene

+0

@rene:はい。あなたはそれを正しく持っています。すべてのxmlノードをキーとして、そのノード内のすべての値を値として返します。日付= 2015-01-02など.... – user2645738

答えて

0

タイプに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();