与LINQ to XML联合

5 c# linq union linq-to-xml openxml-sdk

我需要将两组XElements合并为一组独特的元素.使用.Union()扩展方法,我只得到一个"union all"而不是union.我错过了什么吗?

var elements = xDocument.Descendants(w + "sdt")
                   .Union(otherDocument.Descendants(w + "sdt")
                   .Select(sdt =>
                       new XElement(
                           sdt.Element(w + "sdtPr")
                               .Element(w + "tag")
                               .Attribute(w + "val").Value,
                           GetTextFromContentControl(sdt).Trim())
                   )
               );
Run Code Online (Sandbox Code Playgroud)

Ria*_*Ria 4

您的第一个冲动几乎是正确的。:) 根据David B,如果您没有准确地告诉 LINQ 如何定义相等性,然后给它一堆 XElement,它会通过引用来比较它们。IEqualityComparer\xe2\x80\xb9XElement\xe2\x80\xba幸运的是,您可以通过指定一个(基本上,一个具有 Equals 方法的对象,当两个 XElement 根据您的定义相等时返回 true,否则返回 false,以及一个GetHashCode接受XElement并返回基于哈希码的方法来告诉它使用不同的条件)根据您的平等标准)。

\n

例如:

\n
var elements = xDocument.Descendants(w + "sdt")\n               .Union(otherDocument.Descendants(w + "sdt", new XElementComparer())\n               .RestOfYourCode\n
Run Code Online (Sandbox Code Playgroud)\n

...

\n

项目中的其他地方

\n
public class XElementComparer : IEqualityComparer\xe2\x80\xb9XElement\xe2\x80\xba {\n   public bool Equals(XElement x, XElement y) {\n     return \xe2\x80\xb9X and Y are equal according to your standards\xe2\x80\xba;\n}\n\n\n public int GetHashCode(XElement obj) {\n     return \xe2\x80\xb9hash code based on whatever parameters you used to determine        \n            Equals. For example, if you determine equality based on the ID \n            attribute, return the hash code of the ID attribute.\xe2\x80\xba;\n\n }\n\n }\n
Run Code Online (Sandbox Code Playgroud)\n

注意:我家里没有该框架,因此未测试确切的代码,IEqualityComparer 代码来自此处(向下滚动到第二篇文章)。

\n