【问题标题】:Linq to XMl sorting methodLinq to XML 排序方法
【发布时间】:2010-08-20 00:35:58
【问题描述】:

您好,我有一个手动绑定 XML 的 datagridview。

我希望通过单击列标题对列进行排序。

这是我写的方法:当你点击列标题时,它会抓取列标题并按该列标题对数据进行排序。

我还在上面放了一个切换开关(方向),所以当用户再次点击时,数据可以按不同的顺序(升序/降序)排序

public BindingSource BindXML(string file, string headerName, bool direction)
        {
            XElement record = XElement.Load(file);
            var q = from r in record.Descendants("record")
                    //ascending order?
                    orderby (string)r.Element(headerName)
                    select new
                    {
                        work_pack = (int)r.Element("work_pack"),
                        Locational_Details = (string)r.Element("Locational_Details"),
                        RegimeName = (string)r.Element("RegimeName")
                    };
            if (direction)
            {
                //descending order
                q.OrderByDescending(r => r);
            }

           return new BindingSource(q, null);}

问题是 lambda 表达式 q.OrderByDescending(r => r); 根本不起作用

我什至试过q.OrderByDescending(r => r.RegimeName)

q.OrderByDescending(r => r.Element(headerName));

它们都不起作用。有什么帮助吗?

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    List<T>.Sort() 不同,IEnumerable<T>.OrderBy() 不是就地排序。
    将您的代码更改为q = q.OrderByDescending(r => r.HeaderName);,它应该可以工作

    【讨论】:

      猜你喜欢
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多