简体   繁体   English

使用LINQ C#在XML中使用XElement的值过滤查询

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

Using LINQ C#, I am querying a database table. 使用LINQ C#,我正在查询数据库表。 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. 该表有一个包含XML的列,我想根据XML中等于预定义字符串的元素值来过滤结果。 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 类型'System.Collections.Generic.IEnumerable`1 [System.Xml.Linq.XElement]'的表达式不是序列

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. 我只是试图消除您的语法错误,将Descendants更改为Elements ,该Elements仅需要直接子代。 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. 但是,您必须知道.First()可能不会导致任何元素,然后.Value将引发空引用异常。

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

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