简体   繁体   English

C#-如何使用动态linq为XML查询创建linq

[英]C# - How to use dynamic linq to create linq to XML queries

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. 我有一个要求,即用户必须从UI中以字符串形式提供条件语句,而我必须将条件语句包含在LINQ中以XML查询。 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 我将这个站点用于动态linq查询,但是它只指定LINQ to SQL,而不指定LINQ to XML,这是我需要的

https://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library 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. 流利的语法和查询语法是不同的东西,请不要混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM