Simon
Simon

Reputation: 8357

How to remove an enum item from an array

In C#, how can I remove items from an enum array?

Here is the enum:

public enum example
{
    Example1,
    Example2,
    Example3,
    Example4
}

Here is my code to get the enum:

var data = Enum.GetValues(typeof(example));

How can I remove Example2 from the data variable? I have tried to use LINQ, however I am not sure that this can be done.

Upvotes: 12

Views: 15533

Answers (2)

CharithJ
CharithJ

Reputation: 47530

I have tried to use LINQ, however I am not sure that this can be done.

If you just want to exclude Example2

var data = Enum
    .GetValues(typeof(example))
    .Cast<example>()
    .Where(item => item != example.Example2);

If you want to exclude two or more enums

var data = Enum.GetValues(typeof(example))
    .Cast<example>()
    .Except(new example[] { example.Example2, example.Example3 });

Upvotes: 8

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

You cannot remove it from the array itself, but you can create a new array that does not have the Example2 item:

var data = Enum
    .GetValues(typeof(example))
    .Cast<example>()
    .Where(item => item != example.Example2)
    .ToArray();

Upvotes: 20

Related Questions