Find duplicate xelements

让人想犯罪 __ 提交于 2019-11-29 16:49:30

I suggest, you create a Car class and create a list of Car instances from the XML and do your analysis on that list.
It would simplify things, because you could overwrite the Equals method of the Car class to only return true, if all properties are the same.

This query would result in the list of duplicate Cars entries in your XML, you could take it from there:

XDocument doc = XDocument.Load(@"test.xml");
var duplicates = doc.Descendants("Cars")
                    .GroupBy(c => c.ToString())
                    .Where(g => g.Count() > 1)
                    .Select(g => g.First())
                    .ToList();

There's no point in including more than one node for each duplicate in the list because..well they're duplicates. Similarly you can filter out the nodes that are not duplicates with any other Cars node, just change the where condition:

var uniqueCars = doc.Descendants("Cars")
                    .GroupBy(c => c.ToString())
                    .Where(g => g.Count() == 1)
                    .Select(g => g.First())
                    .ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!