为了使用 LINQ 执行此操作,您需要提取所有数据,然后编写单独的 where 子句以过滤掉您需要的内容。您可以将所有变量作为字符串传递给函数,以便您可以轻松判断什么是空的。这是您要设置的功能:
public List<ListPeople> GetPeopleList(string Name, string opName, string Weight, string opWeight, string DOB, string opDOB)
{
var items = from a in ListPeople
select a;
//--- repeat the section below for Weight and DOB
if (!string.IsNullOrEmpty(Name))
{
switch(opName.ToLower())
{
case "contains":
{
items = items.Where(a => SqlMethods.Like(a.Name, "%" + Name + "%"));
break;
}
case "does not contain":
{
items = items.Where(a => !SqlMethods.Like(a.Name, "%" + Name + "%"));
break;
}
case "is":
{
items = items.Where(a => a.Name == Name));
break;
}
case "is not":
{
items = items.Where(a => a.Name != Name));
break;
}
}
}
//--- end repeat
return items.ToList();
}
祝你好运!
编辑:
自从我在这里回答以来,我找到了一种更好的方法来执行这些类型的查询,它将显着提高性能。结帐http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
此类允许您以字符串格式动态构建 LINQ 查询,然后将其传递给查询。这是我在房地产网站上的房产搜索功能中使用它的一个例子(为了方便而缩小了):
public IQueryable GetSearchResults(string PriceFrom, string PriceTo, string Beds, string Baths, string SqftFrom, string SqftTo, string YearFrom, string YearTo)
{
DatabaseDataContext db = new DatabaseDataContext();
string WhereClause = string.Empty;
if (!string.IsNullOrEmpty(PriceFrom))
WhereClause = "ListPrice >= " + PriceFrom + " AND ";
if (!string.IsNullOrEmpty(PriceTo))
WhereClause += "ListPrice <= " + PriceTo + " AND ";
if (!string.IsNullOrEmpty(Beds))
WhereClause += "Beds >= " + Beds + " AND ";
if (!string.IsNullOrEmpty(Baths))
WhereClause += "FullBaths >= " + Baths + " AND ";
if (!string.IsNullOrEmpty(SqftFrom))
WhereClause += "SqFtHeated >= " + SqftFrom + " AND ";
if (!string.IsNullOrEmpty(SqftTo))
WhereClause += "SqFtHeated <= " + SqftTo + " AND ";
if (!string.IsNullOrEmpty(YearFrom))
WhereClause += "YearBuilt >= " + YearFrom + " AND ";
if (!string.IsNullOrEmpty(YearTo))
WhereClause += "YearBuilt <= " + YearTo + " AND ";
if (WhereClause.EndsWith(" AND "))
WhereClause = WhereClause.Remove(WhereClause.Length - 5);
IQueryable query = db.Listings
.Where(WhereClause)
.OrderBy("ListPrice descending");
return query;
}
祝你好运!