对XElement进行排序 [英] Sorting an XElement
本文介绍了对XElement进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个XElement,其映射如下:
I have a XElement that maps like follows:
<book>
<author>sadfasdf</author>
<title>asdfasdf</title>
<year>1999</year>
</book>
<book>
<author>asdfasdf</author>
<title>asdfasdf</title>
<year>1888</year>
</book>
<book>
<author>asdfsdf</author>
<title>asdfasdf</title>
<year>1777</year>
</book>
如何按作者或书名或年份对书籍分类?谢谢
How can I sort the books by author or title or year? Thanks
推荐答案
您是否要按特定顺序读取(查询)数据,或者您是否真的想对数据重新排序在xml中?要按特定顺序阅读,只需使用LINQ OrderBy
方法:
Do you want to read (query) the data in a specific order, or do you actually want to re-order the data in the xml? To read in a specific order, just use the LINQ OrderBy
method:
var qry = from book in el.Elements("book")
orderby (int)book.Element("year")
select new
{
Year = (int)book.Element("year"),
Title = (string)book.Element("title"),
Author = (string)book.Element("author")
};
(已编辑)更改xml比较棘手...也许像这样:
(edited) Changing the xml is trickier... maybe something like:
var qry = (from book in el.Elements("book")
orderby (int)book.Element("year")
select book).ToArray();
foreach (var book in qry) book.Remove();
foreach (var book in qry) el.Add(book);
这篇关于对XElement进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文