Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 615
proseidon Avatar asked Jul 27 '12 17:07

proseidon


People also ask

How do you check if a list contains any value from another list?

Using any() along with a generator expression: list1 = ['item1','item2','item3'] list2 = ['item4','item5','item3'] if any(x in list1 for x in list2): print("Duplicates found.") else: print("No duplicates found.")

How do I check if an item is in a nested list in Python?

Use the any() function to check if a value exists in a two-dimensional list, e.g. if any('value' in nested_list for nested_list in my_2d_list): . The any() function will return True if the value exists in the list and False otherwise.

How do you check one list against another in Python?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.


1 Answers

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

like image 93
Ani Avatar answered Nov 05 '22 02:11

Ani