2017-11-27 599 views
0

에 따라 종류의 데이터 테이블 나는xml 열 노드 값

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

아래와 같이이

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을 내가 클래스에이 변환이 XML 노드 키 값 쌍으로 그 값을 포함 얻을. 자, 사용자 입력을 기반으로 정렬하고 싶습니다. 예 : 사용자가 날짜 또는 유형 이름을 기준으로 정렬하려는 경우. 그렇게하는 방법? 데이터 테이블에 정렬하거나 목록에 직접 정렬하면됩니다.

나는 datatable에서 정렬하려고했지만 항상 같은 결과를 유지합니다. 동일하게 제안 해주십시오.

+0

그래서 사전에 무엇 :

는이 테스트 장비를 사용하여 위의 코드를 테스트하려면? 이름, 유형, 날짜 값이있는 키는 맞습니까? – rene

+0

@rene : 예. 너는 맞다. 모든 XML 노드를 키로서 그 노드 내부의 모든 값을 값으로 사용합니다. 날짜 = 2015-01-02 등 .... – user2645738

답변

0

유형에 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();