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


I have a string value in column of database table :-

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

There are multiple column with the same format.

Now I need to check ProductAttributeValue and get the data from linQ

currently I am doing by

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();

Is there any way to get direct from linq?


This can be done using 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

Since there is only 1 of each element in the xml data structure you can use Element, if there are multiple you can use Elements and operate on them as a collection.

You can filter elements like usual using Where and other extension methods.

var valToFind = "722";
var val = xml
    .Where(node => node
        ?.Value == valToFind

The above will find the ProductAttribute node that has a ProductAttributeValue Value equal to the valToFind. valToFind is a string for quick comparison against the xml string value.

Answered By – hijinxbassist

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *