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

如何修复“无法将lambda表达式转换为预期委托类型”及“int转bool”错误?

问题分析与解决

错误原因

Where方法的作用是筛选元素,它要求传入的lambda表达式必须返回bool类型(true保留元素,false剔除)。但你的代码里lambda返回的是int类型的距离值,C#不允许将int隐式转换为bool,这就是报错的根源。

两种修正方案(根据实际需求选择)

方案1:筛选距离符合阈值的事件,再取前15个

如果需要先过滤出距离小于某个阈值的事件,再从中取前15个,修改lambda让它返回布尔判断结果即可:

var store = new Dictionary<string, int>();
var maxAllowedDistance = 100; // 替换成你实际需要的距离阈值
var customerCloseEvents = events.Where(x =>
{
    var cacheKey = $"{customer.City}:{x.City}";
    if (store.ContainsKey(cacheKey))
    {
        return store[cacheKey] < maxAllowedDistance; // 返回布尔值判断是否符合条件
    }
    else
    {
        var distance = GetDistance(customer.City, x.City);
        store.Add(cacheKey, distance);
        return distance < maxAllowedDistance;
    }
}).Take(15).ToList();

方案2:按距离排序,取最近的15个事件

如果你的真实需求是获取距离最近的15个事件(原代码逻辑更贴近这个场景),应该用OrderBy(升序,距离从小到大)排序后再取前15个:

var store = new Dictionary<string, int>();
var customerCloseEvents = events.OrderBy(x =>
{
    var cacheKey = $"{customer.City}:{x.City}";
    if (store.ContainsKey(cacheKey))
    {
        return store[cacheKey];
    }
    else
    {
        var distance = GetDistance(customer.City, x.City);
        store.Add(cacheKey, distance);
        return distance;
    }
}).Take(15).ToList();

方案区别

  • 方案1:先筛选符合距离条件的事件,再按原集合顺序取前15个。
  • 方案2:对所有事件按距离从小到大排序,直接取前15个最近的。

内容的提问来源于stack exchange,提问作者Code Haven

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:06:16