使用 Linq c# 检查值是否在列表中

Check if a value is in the list with Linq c#

我有一个列表 public static List<string> HandledErrorCodes { get; } = new List<string> {...,里面有一些数据。我需要检查值 (ex.ErrorCode) 是否在此列表中。我认为最好的方法是使用 Linq:

if ((exception is DomainException ex 
    && CommandTriggerCommon.HandledErrorCodes.Any(ex.ErrorCode))

但我收到错误消息“参数 2:无法从 'string' 转换为 'System.Func<string, bool>'”。最好的方法是什么?

Any 需要 Func<T,bool>(或者在你的特定情况下 Func<string,bool>)——你传递的只是一个 string

应该是... && CommandTriggerCommon.HandledErrorCodes.Any(ec => ec == ex.ErrorCode)

使用List.Contains()查找元素是否存在,而不是Any:

if ((exception is DomainException ex 
    && CommandTriggerCommon.HandledErrorCodes.Contains(ex.ErrorCode))

如果您坚持使用 LINQ(为什么?)您需要将条件指定为 Func<T,bool>

if ((exception is DomainException ex 
    && CommandTriggerCommon.HandledErrorCodes.Any(e=>e==ex.ErrorCode))

这两种方法都会遍历整个列表以找到匹配项。如果您有几十个错误代码,您可以使用 HashSet 而不是 List<string> 来加快速度。 HashSet.Contains 随着项目数量的增加,将比线性搜索快得多。