我正在尝试动态构建一个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;
最佳答案
您可以替换:
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))