C#:使用Lambda根据Slot获取对应Location的代码报错求助
问题分析与修复
你遇到的错误原因很明确:Any()方法需要一个返回布尔值的条件判断逻辑,但你直接写了x => slot——这里的slot是整数类型,编译器无法把它自动转换成bool值,所以才会抛出“Cannot convert int to bool”的错误。
另外还有个隐藏问题:FirstOrDefault()返回的是匹配的Customer对象(找不到匹配项时会返回null),不是直接的int?类型,直接赋值会出现类型不匹配的问题。
修复后的代码(两种常用写法)
写法1:先筛选再投影目标属性
int? location = lstCustomer .Where(c => c.slots.Any(s => s == slot)) // 正确判断目标slot是否在当前Customer的slots列表中 .Select(c => (int?)c.location) // 将location转为可空int,适配无匹配时返回null的场景 .FirstOrDefault();
写法2:先获取匹配对象,再安全访问属性
// 先找到第一个包含目标slot的Customer实例 var matchingCustomer = lstCustomer.FirstOrDefault(c => c.slots.Any(s => s == slot)); // 使用空安全运算符(?.)避免空引用异常,无匹配时返回null int? location = matchingCustomer?.location;
额外补充说明
- 如果你的列表中可能存在多个Customer包含同一个slot,
FirstOrDefault()只会返回第一个匹配的对象。若需要所有匹配的location值,可以改成这样:List<int> allMatchingLocations = lstCustomer .Where(c => c.slots.Any(s => s == slot)) .Select(c => c.location) .ToList(); - 若
Customer的slots属性可能为null,建议在判断时加上空检查,避免空引用异常:c.slots?.Any(s => s == slot) ?? false
内容的提问来源于stack exchange,提问作者Robert Smith
相关产品推荐
相关产品推荐

