I'm trying to have search functionality to my existing IQueryable
object.
Here's my sample class:
public class Fruit {
public string Name {get;set;}
public string Origin {get;set;}
public List<string> Variations {get;set;}
}
and I map them to supply an IQuerayble object.
IQueryable<Fruit> fruits;
if(!string.IsNullOrEmpty(search)){
fruits = fruits.Where(x=>x.Name.Contains(search) || x.Origin.Contains(search));
}
The above sample codes work fine. I was able to return those items depending on my search query.
But when I want to include the searching of Variations
, then it doesn't work.
Here's the sample code that fails in the compiler.
fruits = fruits.Where(x=>x.Name.Contains(search) || x.Origin.Contains(search) || x.Variations.Where(v=>v.Contains(search));
It shows the error
Severity Code Description Project File Line Suppression State
Error CS0019 Operator '||' cannot be applied to operands of type 'bool' and 'IEnumerable<string>'
So far, I have tried this approach:
fruits = fruits.Where(x=>x.Name.Contains(search) || x.Origin.Contains(search) || x.Variations.Contains(search));
But unfortunately, it returns all the list and it seems the search feature doesn't work at all.
CodePudding user response:
Your usage of Where
on the query for variations returns results, rather than doing a conditional operation. If you modify this to something similar to the following you should be ok.
fruits = fruits.Where(x =>
x.Name.Contains(search) // Name contains the item
|| x.Origin.Contains(search) // Orgin Contains
|| x.Variations.Any(v => v.Contains(search)) // Any variation contains the search term
);