سؤال

I am trying to dynamically build an IQueryable that will test to see if a number of strings exists in the description.

using SQL this can be easily achieved by having multiple OR statements.

but how can i do this using LINQ?

here is my code thus far...

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;
هل كانت مفيدة؟

المحلول

You can replace:

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));
    }  
}

by

Results = Results.Where(x => keywords.Any(y=>x.DB_Auction.Description.Contains(y))); 

So, eventually you may want to add this in you LINQ expression:

where keywords.Any(x=>a.Description.Contains(x))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top