myClass
{
.....
.....
public XyzEnum Profession { get; set; }
....
}
I’m trying to use LINQ on list of objects like this.
if(myClassList.Any(x => x.Profession = XyzEnum.SpecificProfession))
{
.....
}
I want to compare int values of enum. How to Cast x.Profession in above code to int? Below code doesn’t work.
if(myClassList.Any(x => (int)x.Profession = (int)XyzEnum.SpecificProfession))
{
.....
}
My aim is to check if specific Profession exist inside list or not.
>Solution :
Seems you mixed up assignment (which is =) with comparison (which is ==). Casting anything to int will therefor have no effect.
So what you presumably need is this:
if(myClassList.Any(x => x.Profession == XyzEnum.SpecificProfession) ...
If your enum can have multiple values, you’re better of using the Enum.HasFlag-method, in order to check if your enum-value contains a specific value:
if(myClassList.Any(x => x.Profession.HasFlag(XyzEnum.SpecificProfession)) ...
However that assumes your enum-values are marked as Flags:
[Flags]enum MyEnum
{
One = 0,
Two = 1,
Three = 2,
Four = 4,
Five = 8 // and so on
}