使用Linq筛选列表
本文关键字:列表 筛选 Linq 使用 | 更新日期: 2023-09-27 18:00:04
我有一个类:
public class Car
{
public string Color { get; set; }
public string Speed { get; set; }
}
还有一个例子:
List<Car> Cars = new List<Car>()
{
new Car()
{
Color = "Green".
Speed = "100"
},
new Car()
{
Color = "Yellow".
Speed = "150"
}
}
我想过滤这个列表
我知道:
List<Car> Conditions = new List<Car>()
{
new Car()
{
Color = "Green".
Speed = "100"
},
new Car()
{
Color = "Yellow".
Speed = "100"
},
.......
}
如何浏览我的列表,只乘坐至少符合Linq条件的汽车?
这里,仅以我列表的第一个索引为例
我的预期输出:
List<Car> Cars = new List<Car>()
{
new Car()
{
Color = "Green".
Speed = "100"
}
}
因为Color AND Speed与Conditions
的一个索引匹配
var FilteredCars = Cars
.Where(car => Conditions.Any(c => car.Color == c.Color && car.Speed == c.Speed));
如果Car
以这种方式覆盖Equals
+GetHashCode
,您也可以使用以下内容:
var FilteredCars = Cars.Where(Conditions.Contains);
如果您需要一套汽车
var result = Cars
.Where(car=>Conditions.Any(cond=>
cond.Speed == car.Speed && cond.Color == car.Color)).ToArray();
如果你只需要一辆车从一组匹配你的条件
var result = Cars
.FirstOrDefault(car=>Conditions.Any(cond=>
cond.Speed == car.Speed && cond.Color == car.Color));