如何根据carspecification的equipmentId筛选匹配的equipment项?
Got it, let's get this filtering working right. The problem with your original code is that carSpecification.Select(y=> y.EquipmentId) returns an entire collection of IDs, and you're trying to compare a single equipment ID to that collection using Equals—that won't work because Equals checks for equality between two single values, not a value and a list.
Here are two straightforward ways to fix this:
Approach 1: Use Contains with a precomputed list of target IDs (most efficient)
First, extract all the EquipmentIds from your carSpecification list into a separate collection, then filter your equipment list to only include items whose Id exists in that collection. Using a HashSet is ideal here because lookups are O(1), which is much faster than a regular list for larger datasets.
// Get your equipment and carSpecification lists as before var equipment = _carService.GetCarEquipment(carId); var carSpecification = _carSpecificationService.GetId(specificationId); // Extract target EquipmentIds into a HashSet for fast lookups var targetEquipmentIds = new HashSet<int>(carSpecification.Select(y => y.EquipmentId)); // Filter equipment to match the target IDs var matchingEquipment = equipment.Where(x => targetEquipmentIds.Contains(x.Id)).ToList();
If your lists are small, a regular List will work too:
var targetEquipmentIds = carSpecification.Select(y => y.EquipmentId).ToList(); var matchingEquipment = equipment.Where(x => targetEquipmentIds.Contains(x.Id)).ToList();
Approach 2: Use Any for readability (simpler for small lists)
If you prefer more readable code and don't need the performance boost of a HashSet, you can use Any to check if there's any matching EquipmentId in the carSpecification list for each equipment item:
var matchingEquipment = equipment .Where(x => carSpecification.Any(y => y.EquipmentId == x.Id)) .ToList();
This works because Any returns true if at least one element in carSpecification has an EquipmentId that matches the current equipment's Id.
Either of these approaches will correctly filter your equipment list to only include items that have an Id present in the carSpecification's EquipmentIds.
内容的提问来源于stack exchange,提问作者casillas

