Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast inside LINQ clause ANY

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading