简体   繁体   English

检查所有值列表是否在枚举C#中

[英]Check all list of values are in the enum c#

I have an integer list containing the ids 我有一个包含ID的整数列表

List<int> ids = new List<int>;

I am adding values in the list 我在列表中添加值

list.Add(100);
list.Add(110);
list.Add(120);

I want to check whether all the values present in the list is present in my enum 我想检查列表中存在的所有值是否都在我的枚举中

public enum IdEnum
{
    IT= 100,
    Bank= 110,
    Insurance= 120,
 }

Currently I am using 目前我正在使用

if (ids.Select(x => x).All(x => Enum.TryParse(x.ToString(), out IdEnum y)))
{
    //All the companies in the list are present in the enum
}
else
{
}

Even if one company in the ids list is different from the enum it should be in else 即使ID列表中的一家公司与枚举不同,它也应该位于其他公司中

In my case in both the cases it is executing the if statement.If all the companies are same as enum or if some of the companies are different from enum ANy help? 在我的两种情况下,它都执行if语句。如果所有公司都与enum相同,或者某些公司与enum不同,则需要帮助吗?

Enum.TryParse returns true for any numeric value. Enum.TryParse对于任何数值返回true。 As per the documentation : 根据文档

If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. 如果value是不表示TEnum枚举的基础值的整数的字符串表示形式,则该方法返回一个枚举成员,该成员的基础值是将值转换为整数类型的值。 If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum . 如果不希望出现这种情况,请调用IsDefined方法以确保整数的特定字符串表示形式实际上是TEnum的成员。

So following the suggestion, just use IsDefined : 因此,按照建议,只需使用IsDefined

if (ids.All(x => Enum.IsDefined(typeof(IdEnum), x)))

You can use Except which is set operation instead of searching each id in enum values 您可以使用设置操作的Except而不是在枚举值中搜索每个id

var allIn = !ids.Except(Enum.GetValues(typeof(IdEnum)).Cast<int>()).Any();

When you use Enum.IsDefined you are doing lot of additional work for each id in list - each values is checked for null, then type of object is verified to be enum, after that type of value is checked, underlying type of enum is checked, array of enum values is retrieved, and binary search in values is performed. 当您使用Enum.IsDefined时,您Enum.IsDefined列表中的每个id做很多额外的工作-检查每个值是否为null,然后验证对象的类型为枚举,在检查了该值的类型之后,检查了枚举的基础类型,检索枚举值的数组,并执行值的二进制搜索。 That is done for each value. 对每个值都完成此操作。

On the other hand, you can get all enum values only once without additional check of value types. 另一方面,您只能一次获取所有枚举值,而无需另外检查值类型。 Then just remove these values from list of ids and check if anything left. 然后只需从ID列表中删除这些值,然后检查是否还有剩余。

if (ids.Select(x => x).All(x => Enum.IsDefined(typeof(IdEnum), x)))
{
    // All the companies in the list are present in the enum
}
else
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM