I had an XML file where I needed to return all records that contained a specific keyword. Each record has multiple keyword values. My first shot at a LINQ query would only return records where the keyword was found in the first occurrence of the keyword value. The second query will return a record with one or more matches for the keyword value.

*** Sample XML ***

<Records>
  <Record>
    <Name>Abdominal Pain</Name>
    <Id>1</Id>
    <Keywords>
      <Value>ABDOMEN</Value>
      <Value>ABDOMINAL CRAMPS</Value>
      <Value>ABDOMINAL PAIN</Value>
      <Value>ABDOMINAL WALL PAIN</Value>
    </Keywords>
  </Record>
</Records>

*** Incorrect LINQ query

var v = from script in _x.Elements(“Script”)
  where script.Element(“Keywords”).Element(“Value”).Value.Contains(t)
  select new {
   ScriptName = script.Element(“Name”).Value,
   ID = script.Element(“Id”).Value
  };

*** Correct LINQ query

XElement _x = XElement.Load(@”c://File.xml”);
// Keyword to search for
string t = “ABDOMEN”;

var v = from script in _x.Elements(“Record”)
  where script.Element(“Keywords”).Elements(“Value”).Any(tx => tx.Value.Contains(t))
  select new {
   ScriptName = script.Element(“Name”).Value,
   ID = script.Element(“Id”).Value
  };
     
foreach (var item in v) {
 Console.WriteLine(item.ScriptName + ” ” + item.ID);
}