简体   繁体   English

匿名 object 上的动态 where 条件

[英]Dynamic where condition on anonymous object

I would like to implement method with input like this:我想用这样的输入来实现方法:

public async Task<IList<T>> Get(Expression<Func<Class1, Class2, Class3, bool>> predicate)
{ 
   var query = from c1 in db.Class1
               from c2 in db.Class2
               from c3 in db.Class3
               select new { c1, c2, c3 };

  return query.Where(predicate).ToListAsync();

}

I want call this method like Get((x, y, z) => x.Prop1 == 1 && y.Prop5 == 4)我想将此方法称为Get((x, y, z) => x.Prop1 == 1 && y.Prop5 == 4)

I've got error:我有错误:

Error CS1503 Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<Class1, Class2, Class3, bool>>' to 
'System.Linq.Expressions.Expression<System.Func<<anonymous type: Class1 pcp, Class2 pc, Class3 bu>, bool>>'

in line containing Where(predicate)在包含Where(predicate)的行中

How to I solve this issue?我该如何解决这个问题?

Since it isn't possible to have your Get method return the anonymous type and you don't pass the anonymous type in (eg with an answer constructor Expression for type inference), you can't use an anonymous type for your query.由于不可能让您的Get方法返回匿名类型并且您不传递匿名类型(例如,使用答案构造函数Expression进行类型推断),因此您不能使用匿名类型进行查询。

Instead create an explicit type and use that for both:而是创建一个显式类型并将其用于两者:

public class CAns {
    public Class1 c1;
    public Class2 c2;
    public Class3 c3;
}

async Task<IList<CAns>> Get(Expression<Func<CAns, bool>> predicate)
{
   var query = from c1 in db.Class1
               from c2 in db.Class2
               from c3 in db.Class3
               select new CAns { c1 = c1, c2 = c2, c3 = c3 };

  return query.Where(predicate).ToListAsync();
}

Then you can call Get with:然后你可以调用Get

var ans = Get(q => q.c1.Prop1 == 1 && q.c2.Prop5 == 4);

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

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