Click here to Skip to main content
15,884,473 members
Articles / Programming Languages / C#

The Enumerable Enumerator

Rate me:
Please Sign up or sign in to vote.
4.80/5 (22 votes)
2 Nov 20062 min read 56.5K   321   43  
Iterate over your enums, and other things to do with enums.
/*
Copyright (c) 2006, Marc Clifton
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list
  of conditions and the following disclaimer. 

* Redistributions in binary form must reproduce the above copyright notice, this 
  list of conditions and the following disclaimer in the documentation and/or other
  materials provided with the distribution. 
 
* Neither the name Marc Clifton nor the names of contributors may be
  used to endorse or promote products derived from this software without specific
  prior written permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

using System;
using System.Collections.Generic;

// Ordinal: Being of a specified position in a numbered series

// The Enumerable Enumerator!

namespace Clifton.Tools.Data
{
    public static class Enumerator<T>
    {
        /// <summary>
        /// Returns the first value in the enumeration, as sorted
        /// by enum value, not ordinal value.
        /// </summary>
        public static T First
        {
            get { return ((T[])Enum.GetValues(typeof(T)))[0]; }
        }

        /// <summary>
        /// Returns the last vaue in the enumeration, as sorted
        /// by enum value, not ordinal value.
        /// </summary>
        public static T Last
        {
            get 
            {
                T[] vals = (T[])Enum.GetValues(typeof(T));
                return vals[vals.Length-1]; 
            }
        }

		public static T PreviousBounded(T val, T min)
		{
			T[] vals = (T[])Enum.GetValues(typeof(T));
			int curIdx = Array.FindIndex<T>(vals, delegate(T v) { return v.Equals(val); });
			int minIdx = Array.FindIndex<T>(vals, delegate(T v) { return v.Equals(min); });

			return curIdx <= minIdx ? vals[minIdx] : vals[curIdx - 1];
		}

		public static T NextBounded(T val, T max)
		{
			T[] vals = (T[])Enum.GetValues(typeof(T));
			int curIdx = Array.FindIndex<T>(vals, delegate(T v) { return v.Equals(val); });
			int maxIdx = Array.FindIndex<T>(vals, delegate(T v) { return v.Equals(max); });

			return curIdx >= maxIdx ? vals[maxIdx] : vals[curIdx + 1];
		}

        /// <summary>
        /// Returns the enumeration value that is previous to the supplied one,
        /// or the first enumeration value, based on enum value, not ordinal value.
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static T PreviousOrFirst(T val)
        {
            T[] vals = (T[])Enum.GetValues(typeof(T));
            int idx = Array.FindIndex<T>(vals, delegate(T v) { return v.Equals(val); });

            return idx == 0 ? vals[0] : vals[idx - 1];
        }

        /// <summary>
        /// Returns the enumeration value that is next to the supplied one,
        /// or the last enumeration value based on enum value, not ordinal value.
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static T NextOrLast(T val)
        {
            T[] vals = (T[])Enum.GetValues(typeof(T));
            int idx = Array.FindIndex<T>(vals, delegate(T v) { return v.Equals(val); });

            return idx == vals.Length-1 ? vals[idx] : vals[idx + 1];
        }

        /// <summary>
        /// Iterates over the enumeration collection by enum value, not ordinal value.
        /// </summary>
        /// <returns></returns>
		public static IEnumerable<T> Items()
		{
			return (T[])Enum.GetValues(typeof(T));
		}
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect Interacx
United States United States
Blog: https://marcclifton.wordpress.com/
Home Page: http://www.marcclifton.com
Research: http://www.higherorderprogramming.com/
GitHub: https://github.com/cliftonm

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions