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

Time:03-03

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?

CodePudding user response:

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
    .Element("Attributes")
    .Element("ProductAttribute")
    .Element("ProductAttributeValue")
    .Element("Value")?.Value;

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
    .Element("Attributes")
    .Elements("ProductAttribute")
    .Where(node => node
        .Element("ProductAttributeValue")
        ?.Element("Value")
        ?.Value == valToFind
    )
    .FirstOrDefault();

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.

  • Related