如何在 C# 中检查来自 linq 的属性值字符串

How to check the attribute value string from linq in c#

我在数据库的列中有一个字符串值 table :-

<Attributes><ProductAttribute ID="322"><ProductAttributeValue><Value>782</Value></ProductAttributeValue></ProductAttribute></Attributes>

有多列格式相同。

现在我需要检查 ProductAttributeValue 并从 linQ 获取数据

目前我在

var id = 782
var string = "<Attributes><ProductAttribute ID="322"><ProductAttributeValue><Value>" + id + "</Value></ProductAttributeValue></ProductAttribute></Attributes>";

var value = sometable.where(x => x.valueString == string).FirstOrDefault();

有什么方法可以直接从 linq 获取吗?

这可以使用 LINQ to XML 来完成。

using System.Linq;
using System.Xml.Linq;
...

var id = "Value To Find";
var str = "<Attributes><ProductAttribute ID=\"322\"><ProductAttributeValue><Value>" + id + "</Value></ProductAttributeValue></ProductAttribute></Attributes>";

var xml = XDocument.Parse(str);
var val = xml
    .Element("Attributes")
    .Element("ProductAttribute")
    .Element("ProductAttributeValue")
    .Element("Value")?.Value;

由于xml数据结构中每个元素只有1个你可以使用Element,如果有多个你可以使用Elements并将它们作为一个集合来操作.

您可以使用 Where 和其他扩展方法像往常一样过滤元素。

var valToFind = "722";
var val = xml
    .Element("Attributes")
    .Elements("ProductAttribute")
    .Where(node => node
        .Element("ProductAttributeValue")
        ?.Element("Value")
        ?.Value == valToFind
    )
    .FirstOrDefault();

以上将查找 ProductAttributeValue 值等于 valToFind 的 ProductAttribute 节点。 valToFind 是一个用于与 xml 字符串值进行快速比较的字符串。