Reputation: 2305
Okay, so let's say I have a List<car>
. Each car also contains a List<part>
. Each part has an ID
associated with it. I'm only given the ID
to a part
, and I want to find the car
that contains that part
. What is the best way to find this car
?
Upvotes: 8
Views: 18811
Reputation: 19203
var id = 123;
var cars = new List<Car>();
var theCar = cars.Single(
car => car.parts
.FirstOrDefault(part => part.Id == id) != null
);
Upvotes: 5
Reputation: 113412
How about with LINQ?
List<Car> cars = ...
var carToFind = cars.FirstOrDefault(car => car.Parts.Any(part => part.Id == idToFind));
In English: "Find the first car (or null if no such car exists) that has any part with an Id matching the desired Id."
Upvotes: 17
Reputation: 25763
Find within a Find
List<car> cars = new List<Car>();
List<car> carWithParts = cars.Find(x => x.parts.Any(y => y.PartID=123));
This will work if multiple cars could contain the same PartID.
Upvotes: 1
Reputation: 2797
How about:
foreach(Car car in listOfCars)
{
if (car.parts.Contains(partID))
{
return car;
}
}
Edit2: Ah, I misunderstood and thought that your car had a list of partIDs.
So, in that case...
foreach(Car car in listOfCars)
{
foreach(Part part in car.parts)
{
if (part.id == partId)
{
return car;
}
}
}
Edit1: Depending on your use case, it might also make sense to maintain an "index" that maps from part IDs to cars. Something like:
var partIDToCar = Dictionary<string, Car>();
As you are putting parts in your cars, you update your index:
partIDToCar[partID] = car;
Then, it's a quick check to get the car:
if (partIDToCar.ContainsKey(partID))
{
return partIDToCar[partID];
}
Upvotes: 1
Reputation: 6026
You could do a LINQ query like this:
// List<car> cars;
int id = 101;
var result = Cars.Where (c => c.parts.Where (p => p.ID == id).Any ());
Upvotes: 2
Reputation: 961
var thePart;
foreach (var part in list<parts>)
{
if (part.id = ID)
thePart = part;
}
foreach (var car in list<cars>)
{
if (car.Part = thePart)
return car;
}
Upvotes: 0