【问题标题】:sort datatable based on xml column node value根据xml列节点值对数据表进行排序
【发布时间】:2017-11-27 09:37:29
【问题描述】:

我得到这样的数据表

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>

我将其转换为如下所示的类

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 包含节点及其值作为键值对。现在,我想根据用户输入对其进行排序。例如如果用户想按日期或类型名称排序。怎么做?在数据表中排序或直接排序到列表中都可以。

我尝试在数据表中排序,但结果始终保持不变。请提供任何相同的建议。

【问题讨论】:

  • 那本词典里有什么?键名称、类型、日期及其值,对吗?
  • @rene:是的。你答对了。所有 xml 节点作为键,该节点内的所有值作为值,例如日期 = 2015-01-02 等....

标签: c# xml list sorting datatable


【解决方案1】:

您可以使用为您的类型实现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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多