如何从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
ITrustbecause 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
相关产品推荐
相关产品推荐

