gpt4 book ai didi

C# Lambda WhereIf 或语句

转载 作者:行者123 更新时间:2023-11-30 12:43:13 24 4
gpt4 key购买 nike

我有许多未知的搜索参数需要评估。我最多只有 5 个搜索级别,目前只显示 3 个级别。我一直在尝试使用 WhereIf 扩展,但也许那不是最好的方法。我更喜欢 lambda 或 linq 语句中的解决方案。这是一个模型:

enter image description here

考虑:

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

关于C# Lambda WhereIf 或语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com