简体   繁体   English

我可以在LINQ表达式中键入要执行的代码吗?

[英]c# can I type the code I want to execute in LINQ expressions

A very simple question. 一个非常简单的问题。 I just happen to be practicing LINQ now, I want to know if I can type the condition in "where" part of LINQ? 我刚好现在正在练习LINQ,我想知道是否可以在LINQ的“哪里”部分键入条件? for example 例如

from a in myPerson
where a.Age > 15
select a;

and then I get to type my own condition in run-time. 然后在运行时输入自己的条件 If I want to get the age greater than 25 this time, or I want to filter it not by age but by Names now. 如果这次我希望年龄大于25岁,或者现在不按年龄而是按姓名过滤。 So I will just type 所以我只输入

where a.Name == "John"

I wonder if it can be done. 我想知道是否可以做到。

Thanks in any help! 谢谢您的帮助!

Instead of hardcoding your value in the condition, use a variable. 可以使用变量来代替对条件中的值进行硬编码。 So your condition can be handled with different values during runtime 因此您的条件可以在运行时用不同的值处理

var age = //put your code for retrieving age
from a in myPerson
where a.Age > age 
select a;

You can compose IQueryables. 您可以编写IQueryable。 Just append additional Where , OrderBy etc clauses as needed: 只需根据需要附加其他WhereOrderBy等子句:

// passed as parameters
int age;
string name;
bool sortByName;

var persons = _dbContext.Person;

// always filter by Age
var result = persons.Where(p => p.Age > age);

// additionally filter by Name if some condition is met
if (age > 25) {
    result = result.Where(p => p.Name == name);
}

// sort depending on parameter
if (sortByName) {
    result = result.OrderBy(p => p.Name);
}
else {
    result = result.OrderBy(p => p.Age);
}

// query will be executed when you enumerate the IQueryable
return result.ToArray();

Make a IQueryable 使一个IQueryable

var ageConditiion = 15;
var originQuery = from a in myPerson select a;
var result1 = originQuery.Where(a => a.Age > ageConditiion).ToList();
var result2 = originQuery.Where(a => a.Name == "John").ToList();

Queryable wont send any request to database. 可查询不会将任何请求发送到数据库。

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

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