Getting more from your enumerations

With LINQ, you can retrieve an enumeration's metadata, such as its minimum and maximum values and whether it contains a given value.

Introduction

I had a situation come up where I needed to test whether a given value in a database fell inside the range of values given by an enumeration. After fussing around with several ways of testing this, I found a simple, elegant solution that seemed worth documenting.

The theory

In the .NET Framework, enumerations are handled by the Enum class. When you have a code such as

the Framework actually creates an instance of Enum and populates it with your values. And like any class, Enum has methods that can be invoked.

The practice

Of interest is the Shared (static in C#) method GetValues, which takes the contents of an enumeration type and returns it as an instance of the System.Array class. If we take this result and convert it to an IEnumerable of a given type, we can use the LINQ extentions to get some useful information about the enumeration.

Share

About the Author

Gregory Gadow is currently a student at Central Washington University, studying for a B.S. in Actuarial Science with plans to graduate in June, 2019. He has been writing code for almost 30 years in more than a dozen programming languages. Previously, he worked for a mid-size brokerage firm as the company's programming department doing VB6, VB.Net, ASP, HTML, XML and SQL. He also held the Series 7 and Series 66 brokerage licenses.