简体   繁体   中英

Check all list of values are in the enum c#

I have an integer list containing the ids

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

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?

Enum.TryParse returns true for any numeric value. 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. 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 .

So following the suggestion, just use 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

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. 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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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