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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.