ksg
ksg

Reputation: 4067

Convert specified items from enum to list?

I have the following item in my enum list

public enum Role
    {
        ED=1,
        CPDHEAD=2,
        CPD=3,
        CENTERMANAGER=4,
        ACCOUNTSHEAD=5,
        MANAGER=6,
        TECHNICALHEAD=7,
        SALESINDIVIDUAL=8,
        ACCOUNTS=9,
        TECHNICALINDIVIDUAL=10
    }

How can I get TechnicalHead and TechnicalIndividual values into List<int>

This is what I've tried but it returns all the values from the enum role

 List<int> _empRolelId = Enum.GetValues(typeof(EnumClass.Role))
                                .Cast<int>()                                    
                                .Select(x => Convert.ToInt32(x))
                                .ToList();

Upvotes: 2

Views: 82

Answers (2)

shree.pat18
shree.pat18

Reputation: 21757

You can filter with a where clause. Also, the select is redundant since you cast as int earlier.

List<int> _empRolelId = Enum.GetValues(typeof(EnumClass.Role))
                            .Cast<int>()
                            .Where(x => x ==  (int)Rextester.Role.TECHNICALHEAD || x == (int)Rextester.Role.TECHNICALINDIVIDUAL)
                            .ToList();

Demo

Upvotes: 4

Cheng Chen
Cheng Chen

Reputation: 43531

Your enum's underlying type is int, so its items can be converted to int explicitly like this:

var _empRolelId = new List<int>();
_empRolelId.Add((int)Role.TECHNICALHEAD);
_empRolelId.Add((int)Role.TECHNICALINDIVIDUAL);

or build the list when intializing:

var _empRoleId = new List<int>
{
    (int)Role.TECHNICALHEAD,
    (int)Role.TECHNICALINDIVIDUAL
};

Upvotes: 7

Related Questions