【问题标题】:How i can compare two parameter using dynamic linq我如何使用动态 linq 比较两个参数
【发布时间】:2019-03-21 23:28:28
【问题描述】:
using system.Linq.dynamic

public class data
 {
  public int column1{ get; set; }
  public int column2{ get; set; }
  public string column3{ get; set; }
 }
List<data> ListOfdata=new List<data>();
for(i=1:i<10;i++)
 {
  data newdata=new data();
  newdata.column1=i;
  newdata.column2=i+1;
  ListOfdata.Add(newdata)
 }

 condition1="column1!=Null AND column1=column2";

 var filter=ListOfdata.where(condition).Tolist();

所以当我通过时在这里

condition="column1!=Null AND column1=3" 我将从 ListOfdata 中获取数据过滤器

但无法获取过滤数据

条件=条件1;

【问题讨论】:

  • 还有什么问题? data 是什么?你应该提供更多关于你的输入数据、你的预期输出以及你得到什么的详细信息。
  • 你试过用'&'代替'AND'吗?
  • 抱歉 HimBromBeere 没有提供正确的详细信息,请现在检查,RobinBennett 在这里“AND”没有问题,但我无法将两列与动态查询进行比较。我可以将 column1 与任何 int 进行比较。或任何字符串值,但不包含另一个变量

标签: c# linq dynamic


【解决方案1】:

我使用了您的代码(稍作调整)并运行:

using System.Collections.Generic;
using System.Linq; 
using System.Linq.Dynamic;

     static void Main(string[] args)
        {
            List<data> ListOfdata = new List<data>();
            for (int i = 1; i < 10; i++)
            {
                data newdata = new data();
                newdata.column1 = i;
                newdata.column2 = i + 1;
                ListOfdata.Add(newdata);
            }

            //below I update the boolean condition, it needs double == for comparison  
            // so column1 == column2-1 will be evaluated correctly
            string condition1 = "column1!=Null AND column1==column2-1";

            //used 'condition1' instead of 'condition'
            var filter = ListOfdata.Where(condition1).ToList();

            // HERE filter.Count() give me 9 !!
        }
    public class data
    {
        public int column1 { get; set; }
        public int column2 { get; set; }
        public string column3 { get; set; }
    }

【讨论】:

  • 请添加一些详细信息,说明为解决问题所做的更改
  • 当然,我只是进行了语法更正,错误代码中的 condition1 包含赋值 (=) 而不是比较 (==),然后将正确的变量传递给最后一行的 Where 子句。
【解决方案2】:

关于如何为 LINQ 创建动态查询有详细的说明:

这个查询: _dbEntities.Customers.Where(cust => cust.CustomerId == 10).FirstOrDefault();

以动态方式看起来像这样:

ParameterExpression pe = Expression.Parameter(Customer, "cust");
var _prpToUse = Expression.Property(pe, "CustomerId"); 
var _cnstToUse = Expression.Constant(10); 
var qry = Expression.Equal(_prpToUse, _cnstToUse);
MethodCallExpression whereExpression = Expression.Call(  
      typeof(Queryable),  
      "Where",  
      new Type[] { lst.ElementType },  
      lst.Expression,  
      Expression.Lambda<Func<Customer, bool>>(qry, new 
      ParameterExpression[] { pe }));  
lstData.Provider.CreateQuery<Customer>(whereExpression).FirstOrDefault();

查看:https://www.c-sharpcorner.com/UploadFile/b1df45/dynamic-query-using-linq/

希望对你有所帮助。

【讨论】:

  • 仅链接的答案有时会过时。而不是依赖外部资源,您应该将相关信息添加到您的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 2014-12-10
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多