I will do my best to explain my headache here.
I've got 2 generic lists that contain the same type and therefore same type of fields:
List<Car> car1 = GetCars1();
List<Car> car2 = GetCars2();
List<Car> finalListOfCars2 = new List<Car>();
so Car has a field called BumperTypeID
I want to compare list car1 with car2 and find those cars from car2 where car2[index].BumperTypeID exists in the list of all BumperTy开发者_如何学运维peIDs in car1's list of BumperTypeIDs. If it's found in car1's list of BumperTypeIDs, great... But I need to then do another check after this to check that ColorIsBlack. And if that second check turns out true, then ok we're good, add the current car2[index] to the finalList.
So I am not sure how to go about this honestly. It's giving me a headache just thinking about it. It's probably not as bad as I think but I can't wrap my head around a good way to approach this in code.
Not exactly clear on what you're looking for overall, but to compare a List to a List you can use the Intersect<T>()
extension method. It will return a list of all the items that exist in both lists.
If you're looking for items that exist in one list but not the other, use the Except<T>()
method.
EDIT: Based on your edits, your code would look something like this:
public void CompareLists(List<Car> carList1, List<car> carList2){
var car1Ids = carList1.Select(l => l.BumperTypeID);
var car2Ids = carList2.Select(l => l.BumperTypeID);
// Find all cars in List2 that have matching BumperTypeID's
// and filter it that list further based on the color.
var matchedIds = car2Ids.Intersect(car1Ids).Where(x => x.Color == Color.Black);
// do your work here.
}
This is the method I've used elsewhere for merging lists of items. You can refer to my answer in another question for further details on it.
EDIT2: Based on your updated question, I've updated the code. This assumes that there's a unique list of BumperTypeIDs in the collection. I think you're solution will be a mixture of this solution with Chris's answer.
Your hunch is right, Linq can make finding the intersection of two lists pretty easy. Use the Intersects method, and pass in your own custom IEqualityComparer which compares two objects in the list to determine if they are the same.
You can then iterate over the intersection of the two sets. For more information about all of the different "Set" operators (Union, Intersect, Except, etc), look here.
Edit:
To add additional filters, just chain additional Linq operators onto this query. For example:
IDList1.Intersects(IdList2, MyIdComparer).Where(entry => entry.SomethingINeedToCheck == true);
Edit Again:
Here is the above clause, but updated for your new edit:
var ResultList = cars1.Intersects(cars2, CarIdComparer).Where(car => car.IsColorBlack).ToList();
IComparer is the way to go.
精彩评论