c#使用一种方法按元素或属性排序
我需要有时按属性排序xml文档,有时候按元素排序,具体取决于文档的类型。我如何在c#中使用一个sortBy方法来解决这个问题? 非常感谢您的帮助! 例如,我的排序键是“bookID”元素或属性,xml文件是:
100 The cat in the hat 90 another book 103 a new book
或者有时xml有以下格式:
The cat in the hat another book a new book
假设您使用Linq-to-XML,则需要在查询中处理这两种可能性。 您可以使用let
关键字,但基本思想是检查属性或元素是否为null并使用适当的值。
var books = from book in document.Element("bookstore").Elements("book") let bookId = book.Attribute("bookID") != null ? book.Attribute("bookID").Value : book.Element("bookID").Value orderby int.Parse(bookId) select book; // project properties of book as needed