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 theIsDefined
method to ensure that a particular string representation of an integer is actually a member ofTEnum
.
So following the suggestion, just use IsDefined
:
if (ids.All(x => Enum.IsDefined(typeof(IdEnum), x)))
See more on this question at Stackoverflow