作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有许多未知的搜索参数需要评估。我最多只有 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
关于C# Lambda WhereIf 或语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876201/
我有许多未知的搜索参数需要评估。我最多只有 5 个搜索级别,目前只显示 3 个级别。我一直在尝试使用 WhereIf 扩展,但也许那不是最好的方法。我更喜欢 lambda 或 linq 语句中的解决方
嗨,有人可以帮助我如何最好地在 LINQ 中使用 whereif IQueryable empQuery; if (empId == "") { empQuer
我正在阅读 this tutorial .我想在 EF Core 中使用 async 查询。 当我这样使用时效果很好: var tasks = await _taskRepository .G
我是一名优秀的程序员,十分优秀!