我在資料庫表的列中有一個字串值:-
<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獲得?
uj5u.com熱心網友回復:
這可以使用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();
以上將找到 ProductAttribute 節點的 ProductAttributeValue 值等于 valToFind。valToFind 是一個字串,用于與 xml 字串值進行快速比較。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438273.html
標籤:C# 网 asp.net-mvc 林克 asp.net 核心
下一篇:序列在linq中不包含元素?
