C# 在列表中查找XmlElement<&燃气轮机;正在使用匹配属性名称的数组。。。使用Linq

C# 在列表中查找XmlElement<&燃气轮机;正在使用匹配属性名称的数组。。。使用Linq,c#,.net,xml,linq,C#,.net,Xml,Linq,我有一个具有多个属性的XmlElement xeObject = <Object Name="Object1" Site="Site1" ... /> l_xeObject = <Object ... /><Object ... /> ... <Object ... /> 其中返回l_xeObject中与xeObject.Name和xeObject.Site具有相同值的任何元素 我能和Linq一起做这个吗 。。。我已经有了以下功能 public

我有一个具有多个属性的XmlElement

xeObject = <Object Name="Object1" Site="Site1" ... />
l_xeObject = <Object ... /><Object ... /> ... <Object ... />
其中返回l_xeObject中与xeObject.Name和xeObject.Site具有相同值的任何元素

我能和Linq一起做这个吗

。。。我已经有了以下功能

public static List<XmlElement> GetXmlElementsFromListWithMatchingAttribute
    (XmlElement xeMatchOn, string sMatchingAttributeName, List<XmlElement> l_xeSearchIn)
{
    return (l_xeSearchIn
        .Where(xe => xe.Attributes[sMatchingAttributeName].Value
            == xeMatchOn.Attributes[sMatchingAttributeName].Value)
        ).ToList();
}
公共静态列表GetXmlElementsFromListWithMatchingAttribute
(XmlElement xeMatchOn,字符串sMatchingAttributeName,列表l_xeSearchIn)
{
返回(l_xen)
.Where(xe=>xe.Attributes[sMatchingAttributeName].Value
==xeMatchOn.Attributes[sMatchingAttributeName].Value)
).ToList();
}
但它只使用一个属性

感谢Frédéric提供了我所需的答案。

您可以使用来匹配多个属性,并避免检查
null

public static IEnumerable<XmlElement> FindMatchingElements(XmlElement match,
    IEnumerable<XmlElement> elements, params string[] attributeNames)
{
    // Argument validation omitted for brevity.

    return elements.Where(
        element => attributeNames.All(
            name => element.GetAttribute(name) == match.GetAttribute(name)));
}
公共静态IEnumerable FindMatchingElements(XmlElement匹配,
IEnumerable元素,参数字符串[]attributeName)
{
//为简洁起见,省略了参数验证。
返回元素。在哪里(
element=>AttributeName.All(
name=>element.GetAttribute(name)==match.GetAttribute(name));
}

,如果您真的想用LINQ解析或生成XML标记,考虑使用DOM类代替.< /P>损坏,谢谢您的响应。我必须将“.Attributes[name]”更改为“.Attributes[name].Value”才能使其正常工作,但这意味着如果我在参数中指定了匹配元素上不存在的属性,我现在会出错@用户597118,关于

.Value
(我不再习惯
XmlElement
,我想对XML来说太多了)。我更新了我的答案以供使用,如果属性不存在,它将返回空字符串。édéric,非常感谢!在某些事情上正确是很好的,只是不要告诉我的太太:-)我只是在阅读LINQtoXML,并且已经看到了它的优点。。。感谢链接和必要的启动a**e!
public static IEnumerable<XmlElement> FindMatchingElements(XmlElement match,
    IEnumerable<XmlElement> elements, params string[] attributeNames)
{
    // Argument validation omitted for brevity.

    return elements.Where(
        element => attributeNames.All(
            name => element.GetAttribute(name) == match.GetAttribute(name)));
}