简体   繁体   中英

Filter a query using value of XElement within XML using LINQ C#

Using LINQ C#, I am querying a database table. The table has a column which contains XML and I would like to filter the results based on an element's value inside the XML being equal to a predefined string. I am using the following query:

(from data in DataObjects.Items
where data.DataItemTimeUtc < DateTime.UtcNow && 
data.DataItemXml.XDocument
   .Descendants("Items")
   .Descendants("MetaData")
   .Descendants("Device")
   .First().Value == "abc123"
orderby data.DataItemTimeUtc descending
select data).ToArray();

but it is failing with an error:

The expression of type 'System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement]' is not a sequence

What about this?

var x = DataObjects.Items
 .Where(data => data.DataItemTimeUtc < DateTime.UtcNow
 && data.DataItemXml.XDocument
  .Elements("Items")
  .Elements("MetaData")
  .Elements("Device")
  .First().Value == "abc123")
 .OrderBy(data => data.DataItemTimeUtc);

I've just tried to remove your syntax errors, changed Descendants to Elements which takes only immediate children. Then I changed it to Method Syntax instead of Expression Syntax to keep things together that belong together. You have to be aware though that the .First() might not result any element and then the .Value will throw a null reference exception.

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