Linq只选择最新的重复项

时间:2017-07-05 13:51:57

标签: c# xml linq

我搜索了帖子,但这让我烦恼: 我试图从XML中删除重复项并保持最新:

XML结构是:

<?xml version="1.0" encoding="utf-8"?>
<scanneditems>
  <item>
    <itemnumber>5701075006328</itemnumber>
    <description>Item 1</description>
    <timestamp>16-06-2017 10:40:39</timestamp>
   </item>
  <item>
    <itemnumber>5701075006328</itemnumber>
    <description>Item 1 duplicate</description>
    <timestamp>08-06-2017 14:25:51</timestamp>
   </item>
</scanneditems>

代码是:

XDocument xDoc = XDocument.Load(@"C:\\fixthis.xml");

var item = xDoc.Element("scanneditems")
    .Elements("item")
    .GroupBy(c => c.Element("itemnumber").Value)

    .OrderByDescending(p => p.Elements("timestamp").ToString());

XDocument doc = new XDocument(new XElement("scanneditems", item));
doc.Save("C:\\fixedfile.xml");

问题:如何将每个副本的结果限制为最新?

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要从每个副本中取出最新项目 因此,在分组项目中使用OrderBy..

XDocument xDoc = XDocument.Load(@"C:\\fixthis.xml");
var items = 
    xDoc.Element("scanneditems")
        .Elements("item")
        .GroupBy(c => c.Element("itemnumber").Value)
        .Select(g => g.OrderByDescending(c => c.Element("timestamp").Value).First());

var doc = new XDocument(new XElement("scanneditems", items));
doc.Save("C:\\fixedfile.xml");