You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据carspecification的equipmentId筛选匹配的equipment项?

Solution to Filter Equipment Matching CarSpecification's EquipmentIds

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:46:20