问题描述
我有一个 List ListPeople名为 ListPeople 的人员列表",对象 People 的类是:
I have a List ListPeople "list of people named ListPeople" and the class for an object People is:
class People
{
public string Name {get;set;}
public DateTime Dob {get;set;}
public int Wieght {get;set;}
}
如何使用用户选择的条件执行搜索:例如:
How could I perform a search with criteria chosen by user: Something like:
例如,如果用户会选择以下内容:
for example if the user would chose something like:
然后我就会知道如何设置该查询:
Then I would know how to set up that query:
var query = (from a in ListPeople
where a.Name == "Tom" &&
a.Weight > 25 &&
a.Dob < "dateTime.Now() - 7 months" // you know what I mean
select a).ToList();
我是否必须构建 4*4*4(所有可能的组合)数量的查询?
do I have to build 4*4*4 (all posible combinations) number of queries?
推荐答案
您不需要提前构建所有可能的组合,您只需要能够继续构建您的查询.草稿:
You do not need to build all possible combinations ahead of time, you just need the ability to keep building upon your query. A rough draft:
var myQuery = ListPeople.AsEnumerable();
if (name.Selection == "Is")
myQuery = myQuery.Where(p => p.Name == nameInput.Text);
else if (name.Selection == /* continues */
您可以继续为每个 UI 元素执行此操作,以便为您的查询构建适当的谓词,然后在完成后,照常对其进行评估.
You can continue doing this for each of your UI elements to build appropriate predicates for your query and then after you're done, evaluate it as normal.
你可以对 Linq-to-SQL 或 EF 做同样的事情,你只是想使用 AsQueryable()
而不是 AsEnumerable()
这样你就可以完成在将其发送到数据库之前进行查询.
You can do the same thing for Linq-to-SQL or EF, you just want to use AsQueryable()
instead of AsEnumerable()
so you can finish the query before sending it against the database.
var myQuery = context.People.AsQueryable();
// continues
这篇关于根据特定条件构建 linq 查询 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!