简体   繁体   English

C#:使用linq检查是否存在特定的属性键值对

[英]C#: Check particular attribute key-value pair is present using linq

I want to check whether a particular attribute key-value pair is present using linq. 我想使用linq检查是否存在特定的属性键值对。
I am using following code to check: 我正在使用以下代码进行检查:

bool keyPresent = xDocument.Element("noSqlDb").Element("elements").Elements("key")
                           .Where(el => el.Attribute("id").Equals(key.ToString()))
                           .Any();  

My XML looks like below: 我的XML如下所示:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<noSqlDb>
  <keytype>System.Int32</keytype>
  <payloadtype>a</payloadtype>
  <elements>
    <key id="1">
      <name>element</name>
      <descr>test element</descr>
      <timestamp>2015-10-02T23:54:07.6562371-04:00</timestamp>
      <children>
        <item>1</item>
        <item>2</item>
        <item>3</item>
      </children>
      <payload>
        <item>CSE681</item>
        <item>SMA</item>
        <item>C#.net</item>
      </payload>
    </key>
  </elements>
</noSqlDb>

You could simply use Xpath to try to find the element. 您可以简单地使用Xpath尝试查找元素。

bool keyPresent = xDocument.XPathSelectElement(String.Format("//key[@id={0}]", key)) != null;

..or using LINQ ..或使用LINQ

bool keyPresent = xDocument.Descendants()
    .Any(e => e.Name == "key" && e.Attributes()
        .Any(a => a.Name == "id" && a.Value == key.ToString()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM