C# 如何使用linq从xml文档中删除重复项?
我有以下代码,需要删除重复的ID并将结果作为字符串返回 scheduledCustomerJourneysXml是一个字符串变量,包含以下xml:C# 如何使用linq从xml文档中删除重复项?,c#,xml,linq,C#,Xml,Linq,我有以下代码,需要删除重复的ID并将结果作为字符串返回 scheduledCustomerJourneysXml是一个字符串变量,包含以下xml: XDocument doc = XDocument.Parse(scheduledCustomerJourneysXml); <ScheduledCustomerJourneys> <ScheduledCustomerJourney ScheduledCustomerJourneyId="534454"
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>
您可以使用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>