Reputation:
I have a class :
public class Car
{
public string Color { get; set; }
public string Speed { get; set; }
}
And one instance :
List<Car> Cars = new List<Car>()
{
new Car()
{
Color = "Green".
Speed = "100"
},
new Car()
{
Color = "Yellow".
Speed = "150"
}
}
I want to filter this List
I do :
List<Car> Conditions = new List<Car>()
{
new Car()
{
Color = "Green".
Speed = "100"
},
new Car()
{
Color = "Yellow".
Speed = "100"
},
.......
}
How to browse my list and take only the car which corresponds at least to a condition with Linq?
Here, take only the first index of my list for example
My expected output :
List<Car> Cars = new List<Car>()
{
new Car()
{
Color = "Green".
Speed = "100"
}
}
Because Color AND Speed match with one index of Conditions
Upvotes: 0
Views: 95
Reputation: 4881
If you need set of cars
var result = Cars
.Where(car=>Conditions.Any(cond=>
cond.Speed == car.Speed && cond.Color == car.Color)).ToArray();
If you need only one car from set of matches to your condition
var result = Cars
.FirstOrDefault(car=>Conditions.Any(cond=>
cond.Speed == car.Speed && cond.Color == car.Color));
Upvotes: 1
Reputation: 460028
var FilteredCars = Cars
.Where(car => Conditions.Any(c => car.Color == c.Color && car.Speed == c.Speed));
If Car
would override Equals
+ GetHashCode
in this way you could also use this:
var FilteredCars = Cars.Where(Conditions.Contains);
Upvotes: 2