Ask Your Question
1

Is it possible to retrieve a collection of Enums while excluding one using Linq?

asked 2023-05-26 01:40:21 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-26 01:57:02 +0000

pufferfish gravatar image

Yes, it is possible to retrieve a collection of Enums while excluding one using Linq.

To exclude a specific Enum value, you can use the Where method in Linq with a condition that checks if the Enum value is not equal to the excluded value.

For example, let's say you have an Enum called Fruit with values Apple, Banana, Orange, and Pear and you want to retrieve a collection of all fruits except for Orange. You can use the following code:

var allFruitsExceptOrange = Enum.GetValues(typeof(Fruit))
                                 .Cast<Fruit>()
                                 .Where(fruit => fruit != Fruit.Orange)
                                 .ToList();

In this code, Enum.GetValues(typeof(Fruit)) retrieves an array of all possible values for the Enum Fruit. The Cast<Fruit>() method converts this array to a collection of Fruit objects. The Where method is then used to filter out any Fruit values that are equal to Fruit.Orange. Finally, the ToList() method is used to convert the filtered results to a List of Fruit values.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-26 01:40:21 +0000

Seen: 1 times

Last updated: May 26 '23