【问题标题】:How to sort XML in LINQ C# by an attribute value? Also MVC如何按属性值对 LINQ C# 中的 XML 进行排序?还有MVC
【发布时间】:2010-02-05 16:58:10
【问题描述】:

(使用最新的 MVC 2 RC 2)我正在尝试按元素的属性值对 LINQ (C#) 中的一些 XML 进行排序...

var sites = from s in xDoc.Element("sites").Elements("site")
orderby s.Attribute("name")
select s;

但是当我将它传递给我的视图时,我得到了异常:

Exception Details: System.ArgumentException: At least one object must implement IComparable.
Source Error: 
Line 37:                </th>
Line 38:            </tr>
Line 39:            <% foreach (var item in Model)
Line 40:               { %>
Line 41:            <tr>

谁能告诉我如何使用 LINQ 对 XML 进行排序并使其正确呈现?

【问题讨论】:

    标签: xml asp.net-mvc linq sorting


    【解决方案1】:

    编辑:好的,我想你只是想要:

    var sites = from s in xDoc.Element("sites").Elements("site")
                orderby (string) s.Attribute("name")
                select s;
    

    也可以写成:

    var sites = xDoc.Element("sites")
                    .Elements("site")
                    .OrderBy(s => (string) s.Attribute("name"));
    

    【讨论】:

    • 对不起,是的,你是对的——我把错误的代码复制到了我的帖子中!啊。我现在已经更正了。
    • “site”变量是我传递给视图的值,例如:return View(site);
    • 您可能希望将 orderby (string) s.Attribute("name") 替换为 orderby s.Attribute("name").Value
    • @VitaliClimenco:这取决于如果元素没有name 属性,您希望发生什么。使用.Value 会抛出异常;使用演员表,它只会在开始时排序(就像空值一样)。
    猜你喜欢
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多