我有两个文档,我需要比较一个简单的架构:
目前的文件:
<Sections>
<Section Number="1"/>
<Section Number="2"/>
<Section Number="4"/>
<Section Number="5"/>
</Sections>
之前的文档:
<Sections>
<Section Number="1"/>
<Section Number="2"/>
</Sections>
比较的结果将是已添加到当前文档的列表部分...即当前文档中不在先前文档中的部分。在本例中,第4节和第5节是新的。
当前和以前的文档可以拥有超过20,000条记录。以下方法产生了我需要的结果,但似乎是错误的方法,因为它多次遍历数据集,并且需要一段时间才能运行。
获取部分列表:
List<XElement> currenList = currentDoc.Descendants("Section").ToList();
获取上一个列表中的属性
List<string> previousString = //get the attribute values...
//get the new sections...
var newSections = (from nodes in currentList
let att = nodes.Attribute("Number").Value
where !previousList.Contains(att)
select nodes)
什么是更好的方法,涉及更少的数据集传递/转换?
答案 0 :(得分:0)
你应该看看Except
:
IEnumerable<int> currentList = currentDoc.Descendants("Section")
.Select(e => (int)e.Attribute("Number"));
IEnumerable<int> previousList = previousDoc.Descendants("Section")
.Select(e => (int)e.Attribute("Number"));
IEnumerable<int> newSections = currentList.Except(previousList);
答案 1 :(得分:0)
您可以使用有序集来跟踪。
SortedSet<string> sections = new Sort...
List<XElement> diff = new Li...
foreach (var node in previousList)
sections.Add(node.Attribute("Section").Value());
foreach (var node in currentList)
if (!sections.Contains(node.Attribute("Section").Value());
diff.Add(node);
这对SortedSet使用了一点额外的内存,但它应该运行n * log(n),因为有序集合上的Contains()将运行log(n)。
最后,diff应包含您正在寻找的列表。