我有许多未知的搜索参数需要评估。最多我只有5个搜索级别,目前仅显示3个级别。
我一直在尝试使用WhereIf扩展名,但这也许不是最好的方法。我希望使用lambda或linq语句中的解决方案。这是一个模型:
考虑:
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
原谅我,我意识到这是不完整的。我开始这样做,但后来意识到这将变得复杂。
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();
提前致谢。
最佳答案
您根本不需要WhereIf就可以完成同一件事。
var result = !String.IsNullOrEmpty(searchVar) ?
animals.Where(x => x.Color == "white" ||
x.Breed == "terrier") : new List<Animal>();
您可能只希望它搜索通过的搜索词。
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
编辑:在linqpad中运行了一个测试,它似乎运行良好。
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; }
}
返回值:
List<Animal> (2 items)
Animal_ID Color Breed
2 white other
3 blue terrier