Check if a value is in the list with Linq c#
I have a List public static List<string> HandledErrorCodes { get; } = new List<string> {...
with some data inside. And i need to check, if a value (ex.ErrorCode) is inside this list. I thing the best way is with 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>'". What is the best way to do that?
Use List.Contains() to find if an element exists, not 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>
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.Contains
will be far faster than a linear search as the number of items grows.
Any
takes Func<T,bool>
(or in your specific case Func<string,bool>
) - you're passing it just a string
It should be ... && CommandTriggerCommon.HandledErrorCodes.Any(ec => ec == ex.ErrorCode)