2

我正在尝试动态构建一个 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;
4

1 回答 1

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))
于 2013-09-16T11:41:00.913 回答