简体   繁体   English

如何在LINQ的where子句中传递动态条件?

[英]How to Pass dynamic condition in where clause in LINQ?

How can I write a dynamic query, and how to pass it into a where condition?如何编写动态查询,以及如何将其传递给 where 条件?

var query = "Name = 'Test'";

//Get data by passing dynamic query
var result = from Table01 in T0001
    where(query)
    select Table01 ;

You can use System.Linq.Dynamic so that you can build query dynamically:您可以使用System.Linq.Dynamic以便您可以动态构建查询:

var query = "Name == \"Test\"";

var result = dbContext.T0001.Where(query).ToList();

You add a reference to System.Linq.Dynamic or System.Linq.Dynamic.Core depending on the kind of project you have (it's a lot easier to get the deprecated package to play nice with a framework winforms project for example) and the flavour of .net it uses - see https://dynamic-linq.net/ for example use.您添加对System.Linq.DynamicSystem.Linq.Dynamic.Core的引用,具体取决于您拥有的项目类型(例如,让弃用的包与框架 winforms 项目配合使用要容易得多)和风格它使用的 .net - 例如使用https://dynamic-linq.net/

The code would be pretty much as you have there except you wouldn't use apostrophes to delimit the string because apostrophes are for chars.代码将与您在那里拥有的几乎一样,只是您不会使用撇号来分隔字符串,因为撇号用于字符。 You could use \\" but the more typical way to do it is like您可以使用\\"但更典型的做法是

Where("Name = @0", "Test")

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

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