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

如何从Dictionary<string, IList<ITrust>>中的列表移除单个ITrust对象?

从Dictionary<string, IList>中移除指定对象的问题

我有一个带Id字段的接口ITrust,还有一个类型为Dictionary<string, IList<ITrust>>的字典。现在想从字典内的列表中移除单个对象,但试了多种脚本都没实现。

我尝试过如下代码:

dictionaryName[keyName].Remove(x => x.Id == Id);

运行后抛出异常:

Cannot convert lambda expression to type ITrust because it is not a delegate type

请问有没有正确的实现代码,或者我的思路是否存在问题?


解决方法

问题出在IList<T>.Remove的参数要求上——它只接受要移除的具体对象实例,不支持用lambda表达式做条件匹配。要实现按Id移除,得先找到符合条件的对象,再调用Remove方法:

// 先获取对应key的列表
var trustList = dictionaryName[keyName];
// 找到要移除的对象
var itemToRemove = trustList.FirstOrDefault(x => x.Id == Id);
// 找到就移除
if (itemToRemove != null)
{
    trustList.Remove(itemToRemove);
}

如果用的是.NET 6及以上版本,也可以写得更简洁:

dictionaryName[keyName].Remove(dictionaryName[keyName].FirstOrDefault(x => x.Id == Id));

不过要注意,FirstOrDefault返回null时,Remove(null)不会报错但也不会执行任何操作。

另外,如果不确定字典里有没有对应的key,建议先判断,避免触发KeyNotFoundException:

if (dictionaryName.TryGetValue(keyName, out var trustList))
{
    var itemToRemove = trustList.FirstOrDefault(x => x.Id == Id);
    if (itemToRemove != null)
    {
        trustList.Remove(itemToRemove);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:35:16