Finding an item within a list within another list?

14,967

Solution 1

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."

Solution 2

var id = 123;
var cars = new List<Car>();
var theCar = cars.Single(
          car => car.parts
                    .FirstOrDefault(part => part.Id == id) != null
          );

Solution 3

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 ());

Solution 4

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];
}

Solution 5

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.

Share:
14,967
proseidon
Author by

proseidon

Updated on June 19, 2022

Comments

  • proseidon
    proseidon almost 2 years

    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?