【问题标题】:C# - How to use dynamic linq to create linq to XML queriesC# - 如何使用动态 linq 创建 linq to XML 查询
【发布时间】:2017-12-03 20:23:38
【问题描述】:

我有一个要求,用户将提供条件语句作为来自 UI 的字符串,我必须将其合并到我的 LINQ to XML 查询中。 我将此站点用于动态 linq 查询但它只指定 LINQ to SQL 而不是 LINQ to XML,这是我需要的

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

我尝试编辑它以满足我的要求,但它似乎不起作用。

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

当这段代码运行时,我得到了错误

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

知道如何解决这个问题吗?

【问题讨论】:

  • 我正在尝试实现动态 LINQ 查询。我希望从用户输入中提取 where 子句中的语句。该语句将作为字符串传递。

标签: c# linq xml-parsing linq-to-xml dynamic-linq


【解决方案1】:
XElement results = XElement.Parse(xml);
var query = results.Elements("Result").AsQueryable().OrderBy(x=>x.Element("Name").Value).ThenBy(x=>x.Element("Phone").Value);

Fluent 语法和查询语法是不同的东西,不要混淆。

【讨论】:

  • 我正在尝试实现动态 LINQ 查询。我希望从用户输入中提取 where 子句中的语句。该语句将作为字符串传递。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
相关资源
最近更新 更多