[英]Check if string list contains any enum string value
enum KnownError
{
[StringValue("CODE-001")]
CODE001,
[StringValue("CODE-002")]
CODE002,
[StringValue("CODE-003")]
CODE003,
[StringValue("CODE-004")]
CODE004,
[StringValue("CODE-005")]
CODE005
}
List<string> errors = {"ahah", "eheh", "CODE-005", "uhuh"};
Let's say i have a list of string errors. 假设我有一个字符串错误列表。 How can I check if any error is "known"?
如何检查“已知”错误?
bool ContainsKnownError(List<string> error)
{
return errors.Where(error => Enum.IsDefined(typeof(KnownError), error) == true).Count() > 0;
}
This doesn't seem to work. 这似乎不起作用。 How can I access StringValue inside the linq query without having to compare each string?
如何在linq查询中访问StringValue而不必比较每个字符串?
EDIT 编辑
I tried @AK_ solution, using Intersect, but I'm getting this compilation error: 我使用Intersect尝试了@AK_解决方案,但出现此编译错误:
The type arguments for method 'System.Linq.Enumerable.Intersect<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Collections.Generic.IEnumerable<TSource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
The real scenario is an Error object with a string field with the code like this 真正的场景是一个Error对象,其中包含一个带有如下代码的字符串字段
class Error { string code; }
List<Error> errors = GetErrors();
var knownErrors = Enum.GetValues(typeof(KnownError));
bool exists = errors.Select(error => error.code).Intersect(knownErrors).Any();
var knownErrors = Enum.GetValues(typeof(KnownError));
return errors.Contains(error => knownErrors.Contains(error));
//or cooler:
return errors.Intersect(knownErrors).Count() > 0;
Zack's comment is correct: return errors.Intersect(knownErrors).Any
is better... +1 him :-) Zack的评论是正确的:
return errors.Intersect(knownErrors).Any
有更好的方法了……+ 1他:-)
Enum.IsDefined
expects an object-wrapped instance of the enum
. Enum.IsDefined
需要enum
的对象包装实例。 Passing a string name does not produce the desired result. 传递字符串名称不会产生期望的结果。
This should work: 这应该工作:
KnownError ignore;
var res = errors.Any(errorCode => Enum.TryParse<KnownError>(errorCode, out ignore));
Note the use of LINQ's Any
in place of comparing Count()
to zero: this approach is more efficient, because it stops as soon as it finds the first match. 请注意,使用LINQ的
Any
来代替将Count()
与零进行比较:这种方法效率更高,因为一旦找到第一个匹配项,它就会停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.