我正在尝试动态构建一个IQueryable,它将测试以查看描述中是否存在多个字符串。
使用SQL可以通过多个OR语句轻松实现。
但我怎么能用LINQ做到这一点?
这是我到目前为止的代码......
List<string> keywords = new List<string>() { "BMW", "M3" };
IQueryable<AuctionVehicle> Results =
from a in DBContext.tbl_Auction
join v in DBContext.tbl_Vehicle on a.VehicleID equals v.VehicleID
where v.Fuel.Equals(Fuel)
&& v.Transmission.Equals(Transmission)
&& a.EndDate < DateTime.Now
select new AuctionVehicle()
{
DB_Auction = a,
DB_Vehicle = v
};
// Keywords
if (keywords.Count == 1)
{
Results = Results.Where(x => x.DB_Auction.Description.Contains(keywords[0]));
}
else if (keywords.Count > 1)
{
// ****************************
// How can i add multiple OR statements??
// ****************************
Results = Results.Where(x => x.DB_Auction.Description.Contains(keywords[0]));
foreach (string keyword in keywords)
{
Results = Results.Where(x => x.DB_Auction.Description.Contains(keyword));
}
}
return Results;
答案 0 :(得分:2)
您可以替换:
if (keywords.Count == 1)
{
Results = Results.Where(x => x.DB_Auction.Description.Contains(keywords[0]));
}
else if (keywords.Count > 1)
{
Results = Results.Where(x => x.DB_Auction.Description.Contains(keywords[0]));
foreach (string keyword in keywords)
{
Results = Results.Where(x => x.DB_Auction.Description.Contains(keyword));
}
}
通过
Results = Results.Where(x => keywords.Any(y=>x.DB_Auction.Description.Contains(y)));
所以,最后你可能想在LINQ表达式中添加它:
where keywords.Any(x=>a.Description.Contains(x))