我正在使用 Linq 尝试过滤掉任何具有相同“名称”属性值的重复 XElement。
原始xml:
<foo>
<property name="John" value="Doe" id="1" />
<property name="Paul" value="Lee" id="1" />
<property name="Ken" value="Flow" id="1" />
<property name="Jane" value="Horace" id="1" />
<property name="Paul" value="Lee" id="1" />
... other xml properties with different id's
</foo>
// project elements in group into a new XElement
// (this is for another part of the code)
var props = group.data.Select( f => new XElement("property",
new XAttribute("name", f.Attribute("name").Value), f.Attribute("value"));
// filter out duplicates
props = props.Where(f => f.ElementsBeforeSelf()
.Where(g => g.Attribute("name").Value ==
f.Attribute("name").Value)
.Count() == 0);
不幸的是,过滤步骤不起作用。我认为 Where() 过滤器会检查当前元素之前具有相同属性名称的任何元素,然后将其包含在大于零的集合中,从而排除当前元素(称为“f”),但仅此而已没有发生。想法?