0

Here is enum;

   public enum myEnum{   
    A= 1,
    B= 2,
    C= 3,
    D= 4,
}

I need a List contains all except D, this way its works;

List<Enum>{myEnum.A, myEnum.B, myEnum.C}

but of course its extremely ugly. How can directly convert and filter D of this enum

Trevor
  • 7,777
  • 6
  • 31
  • 50
TyForHelpDude
  • 4,828
  • 10
  • 48
  • 96

3 Answers3

7
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Where(x => x != MyEnum.D).ToList();
Sam
  • 1,634
  • 13
  • 21
2

You can convert an enum to a list like this:

var enumList = Enum.GetValues(typeof(myEnum)).Cast<myEnum>().ToList();

And to remove myEnum.D, simply call the Remove method:

var enumList = Enum.GetValues(typeof(myEnum)).Cast<myEnum>().ToList().Remove(myEnum.D);

As mentioned in the comments, you could also add only the Enums values, which are not myEnum.D:

var enumList = Enum.GetValues(typeof(myEnum)).Cast<myEnum>().ToList().Where(val => val != myEnum.D);
Moritz Schmidt
  • 2,635
  • 3
  • 27
  • 51
  • 1
    It's better to use a `where` instead of adding the ones you want to a list and then removing ... – Trevor May 21 '19 at 13:01
1

You can get all the values of an enum by calling Enum.GetValues(type) (https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=netframework-4.8)

After getting all the values you can exclude certain values you don't want:

public class Program
{
    public static void Main()
    {
        var allValues = Enum.GetValues(typeof (MyEnum))
            .Cast<MyEnum>()
            .Except(new[]{MyEnum.D})
            .ToArray();

        foreach (var val in allValues)
        {
            Console.WriteLine(val);
        }
    }
}

public enum MyEnum
{
    A,
    B,
    C,
    D
}

This will output:

A B C

https://dotnetfiddle.net/hdZmAK

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77