C# - How to use dynamic linq to create linq to XML queries

c# dynamic-linq linq linq-to-xml xml-parsing

Question

I have a requirement where the users will provide conditional statements as a string from a UI, which I have to incorporate in my LINQ to XML queries. I referred this site for dynamic linq queries But it only specifies LINQ to SQL and not LINQ to XML, which is what i need

https://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library

I tried editing this to fit my requirement, but it doesnt seem to work.

    string xml = @"
               <Results>
                    <Result>
                        <Name>John</Name>
                        <Phone>110</Phone>
                        <Location>USA</Location>
                    </Result>
                    <Result>
                        <Name>Mary</Name>
                        <Phone>120</Phone>
                        <Location>UK</Location>
                    </Result>
                    <Result>
                        <Name>John</Name>
                        <Phone>130</Phone>
                        <Location>Canada</Location>
                    </Result>
              </Results>
       ";

        XElement results = XElement.Parse(xml);
        var query = results.Elements("Result")
                           .AsQueryable().
                           .OrderBy("Element(XName.Get(\"Name\")).Value 
                            ascending, Element(XName.Get(\"Phone\")).Value ascending");


        foreach (var i in query)
        {
            Console.WriteLine(i);
        }

When this code runs, I get the error

System.Linq.Dynamic.ParseException' occurred in System.Linq.Dynamic.dll 
Additional information: No property or field XName' exists in type 'XElement'

Any idea how to fix this?

1
0
7/6/2017 3:15:30 PM

Popular Answer

XElement results = XElement.Parse(xml);
var query = results.Elements("Result").AsQueryable().OrderBy(x=>x.Element("Name").Value).ThenBy(x=>x.Element("Phone").Value);

Fluent syntax and query syntax are different things, don't mix them up.

0
6/30/2017 5:20:33 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow