How to select XElements where Attribute ... (LINQ2XML)

How can I choose a value where id == id && key == key with Linq

XML:

<Localization>    
  <Module id="Customers">
    <CultureCode>de-DE</CultureCode>
    <Key>General</Key>
    <Value>Allgemeine Kunden</Value>
  </Module>     
  <Module id="Contract">
    <CultureCode>de-DE</CultureCode>
    <Key>General</Key>
    <Value>Allgemeine Verträge</Value>
  </Module>     
</localization>

this is my approach

methode (string module, string key) ...

var value = (from l in localization.Elements("Localization").Elements("Module")
             where l.Attribute("id").Equals(module) && l.Element("Key").Value.Equals(key)
             select l.Element("Value").Value);
+3
source share
1 answer

Assuming what moduleis a string, the problem is what you are comparing XAttributewith string.

Here's a fixed version of the request:

var value = (from l in localization.Elements("Localization").Elements("Module")
             where (string) l.Attribute("id") == module && 
                   l.Element("Key").Value == key
             select l.Element("Value").Value);

Note that I use XAttributefor the string, not for the property Value, so if the attribute iddoes not exist, it simply will not match, not explode.

, Single, First, SingleOrDefault FirstOrDefault , .

+7

Source: https://habr.com/ru/post/1713950/


All Articles