[英]Filter list with Linq
我有一堂課:
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"
}
}
因為顏色和速度與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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.