简体   繁体   中英

LINQ to query result from XDocument

I have all the data elements stored from a resource file as follows:

XDocument xDocTranslated = XDocument.Load(TranslatedFile);
var resultTranslated = from item in xDocTranslated.Descendants("data")
select new
{
    Name = (string)item.Attribute("name"),
    Value = (string)item.Element("value")
};

I have a list of strings that I want to compare against the result above and if they match I want to store the new value.

I'm trying something like this:

//Get each string that i want to translate
foreach (var name in StringsToTranslatelist)
{
    //Look up the translated value from data extracted from xml file
    var value= from entry in resultTranslated
        where entry.Name == name;                  <--this does not work

}

WHat is the LINQ statement that I should be using here?? How do I search the resultTranslated ??

It looks like you want to get just the matching value for the specified name, in which case you want to use a standard query operator that will return a scalar value, such as Single :

var value = resultTranslated.Single(r => r.Name == name).Value;

Single will throw an exception if there is no match or if there is more than one match.

Alternatively, you could use First if you want to get the first result (and throw an exception if there are none), or SingleOrDefault or FirstOrDefault and do null checks yourself depending on your requirements.

I believe you want to get value by name:

foreach (var name in StringsToTranslatelist)
{
    var data =  resultTranslated.FirstOrDefault(e => e.Name == name);
    if (data != null)
    {
        // match is found, you can use value
        var value = data.Value;
    }
}

But more efficient way to do this is simply convert you resultTranslated to dictionary:

var data = resultTranslated.ToDictionary(x => x.Name, x => x.Value);

Then you will be able to get values by name

if (data.ContainsKey(name))
    value = data[name];

//Look up the translated value from data extracted from xml file

To me that immediately looks like a dictionary lookup would be the most natural fit.

So the code might be:

//creating the dictionary from the xml doc
var resultTranslatedLookup = xDocTranslated.Descendants("data")
                     .ToDictionary(keyItem => keyItem.Attribute("name").Value
                     , valItem => valItem.Element("value").Value);

//now usage
foreach (var name in StringsToTranslatelist)
{
    string result;
    if (resultTranslatedLookup.TryGetValue(name, out result))
    {
        //do your thing
    }
}

Hope the ToDictionary call is clear, that's just a key and value selector, equivalent to your select new.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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