C # Lambda WhereIf or expression

I have many unknown search options to evaluate. In the best case, I would have only 5 search levels, which at the moment showed only 3 levels. I am trying to use the WhereIf extension, but maybe this is not the best way. I would prefer a solution in lambda or linq expression. Here is the layout:

enter image description here

Consider:

Animal_ID Breed Color Age Weight 1 Poodle White 3 10 2 Shepard Brown 4 15 3 Afghan Brown 9 40 4 Terrier White 7 25 5 Maltese White 12 14 

Forgive me, I understand that this is incomplete. I started to do this, but then I realized that it would be difficult.

 List<Animal> animals = db.Animals //I know I can do this. //.WhereIf(!String.IsNullOrEmpty("Search"), x => (x.Color == "white") || (x.Breed == "terrier")) //I want "OR" here .WhereIf(!String.IsNullOrEmpty("Search_1_IsSomething"), x => (x.Color == "white")) // OR .WhereIf(!String.IsNullOrEmpty("Search_2_OR_IsSomething"), x => (x.Breed == "terrier")) .ToList(); 

Thanks in advance.

+4
source share
2 answers

You can do the same without WhereIf at all.

 var result = !String.IsNullOrEmpty(searchVar) ? animals.Where(x => x.Color == "white" || x.Breed == "terrier") : new List<Animal>(); 

You might just want it to look up the one passed in the search query.

 var result = !String.IsNullOrEmpty(searchVar) ? animals.Where(x => x.Color == searchVar || x.Breed == searchVar) : new List<Animal>(); //or return full list (animals) if search term is null 

Edit: run the test in linqpad and it seems to work fine.

 void Main() { SearchAnimals("white").Dump(); } public List<Animal> SearchAnimals(string searchVar) { var animals = new List<Animal>() { new Animal { Animal_ID = 1, Color = "black", Breed = "other" }, new Animal { Animal_ID = 2, Color = "white", Breed = "other" }, new Animal { Animal_ID = 3, Color = "blue", Breed = "terrier" }, new Animal { Animal_ID = 4, Color = "green", Breed = "other" } }; var result = !String.IsNullOrEmpty(searchVar) ? animals.Where(x => x.Color == "white" || x.Breed == "terrier") : new List<Animal>(); return result.ToList(); } public class Animal { public int Animal_ID { get; set; } public string Color { get; set; } public string Breed { get; set; } } 

Return:

 List<Animal> (2 items) Animal_ID Color Breed 2 white other 3 blue terrier 
+1
source

I think you are asking how to use the second extension method to indicate "or." With Linq, this is not possible, and by the nature of Linq.

As soon as you call Where/WhereIf or any similar method, the enumerable is filtered to the appropriate objects. Calling additional filtering methods for the returned result will not add objects back: it can delete only more objects.

0
source

All Articles