[英]Check if a value is in the list with Linq c#
I have a List public static List<string> HandledErrorCodes { get; } = new List<string> {...
我有一个 List
public static List<string> HandledErrorCodes { get; } = new List<string> {...
public static List<string> HandledErrorCodes { get; } = new List<string> {...
with some data inside. public static List<string> HandledErrorCodes { get; } = new List<string> {...
里面有一些数据。 And i need to check, if a value ( ex.ErrorCode ) is inside this list.我需要检查一个值( ex.ErrorCode )是否在这个列表中。 I thing the best way is with Linq:
我认为最好的方法是使用 Linq:
if ((exception is DomainException ex
&& CommandTriggerCommon.HandledErrorCodes.Any(ex.ErrorCode))
But i'm getting an error "Argument 2: cannot convert from 'string' to 'System.Func<string, bool>'".但我收到一个错误“参数 2:无法从 'string' 转换为 'System.Func<string, bool>'”。 What is the best way to do that?
最好的方法是什么?
Use List.Contains() to find if an element exists, not Any
:使用List.Contains()来查找元素是否存在,而不是
Any
:
if ((exception is DomainException ex
&& CommandTriggerCommon.HandledErrorCodes.Contains(ex.ErrorCode))
If you insist on using LINQ (why?) you need to specify the condition as a Func<T,bool>
如果您坚持使用 LINQ(为什么?)您需要将条件指定为
Func<T,bool>
if ((exception is DomainException ex
&& CommandTriggerCommon.HandledErrorCodes.Any(e=>e==ex.ErrorCode))
Both methods will iterate over the entire list to find matches.这两种方法都将遍历整个列表以查找匹配项。 If you have more than a few dozen error codes you can speed this up by using a HashSet instead of a
List<string>
.如果您有超过几十个错误代码,您可以使用HashSet而不是
List<string>
来加快速度。 HashSet.Contains
will be far faster than a linear search as the number of items grows.随着项目数量的增加,
HashSet.Contains
将比线性搜索快得多。
Any
takes Func<T,bool>
(or in your specific case Func<string,bool>
) - you're passing it just a string
Any
需要Func<T,bool>
(或在您的特定情况下Func<string,bool>
) - 您只是传递一个string
It should be ... && CommandTriggerCommon.HandledErrorCodes.Any(ec => ec == ex.ErrorCode)
它应该是
... && CommandTriggerCommon.HandledErrorCodes.Any(ec => ec == ex.ErrorCode)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.