proseidon
proseidon

Reputation: 2305

Finding an item within a list within another list?

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

Answers (6)

Guvante
Guvante

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

Ani
Ani

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

Matthew
Matthew

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

Nogwater
Nogwater

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

Brad Rem
Brad Rem

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

Kulingar
Kulingar

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

Related Questions