【问题标题】:How do i remove duplicates from xml doc using linq?如何使用 linq 从 xml 文档中删除重复项?
【发布时间】:2021-08-13 02:32:07
【问题描述】:

我有以下代码,需要删除重复的 Id 并将结果作为字符串返回?

scheduledCustomerJourneysXml 是一个包含以下 xml 的字符串变量:

XDocument doc = XDocument.Parse(scheduledCustomerJourneysXml);


<ScheduledCustomerJourneys>
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534454" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534455" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534455" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="538020" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="538020" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="538020" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="538020" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="531228" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534457" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="526977" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="526978" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="538023" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534459" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534459" />
</ScheduledCustomerJourneys>

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: c# xml linq


【解决方案1】:

您可以使用GroupBy 查找重复项,然后删除内存中的重复项并返回字符串表示形式:

doc.Descendants("ScheduledCustomerJourney")
        .GroupBy(x => x.Attribute("ScheduledCustomerJourneyId").Value)
        .SelectMany(x => x.Key == string.Empty ? x : x.Skip(1))
        .Remove();

Console.WriteLine(doc.ToString());

输出:

<ScheduledCustomerJourneys>
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534454" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534455" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="538020" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="531228" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534457" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="526977" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="526978" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="538023" />
  <ScheduledCustomerJourney ScheduledCustomerJourneyId="534459" />
</ScheduledCustomerJourneys>

working DEMO Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多