NetInverse Developers Blog

April 4, 2009
Category: .Net — Tags: , , , , — admin @ 5:23 pm

Following utility function EnumToArray takes an enum type and returns an array populated with each enum item. You can tweak the code a little bit to make the function to be EnumToList easily.

The sample code also demonstrates how to use Enumerable.Except to get the delta of two arrays of same type T.

using System;
using System.Collections.Generic;
using System.Linq;

namespace IEnumerableTest
{
    public static class Utils
    {
        public static T[] EnumToArray<T>()
        {
            Type enumType = typeof(T);
            if (enumType.BaseType != typeof(Enum))
            {
                throw new ArgumentException("T must be a System.Enum");
            }
            return (Enum.GetValues(enumType) as IEnumerable<T>).ToArray();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Convert Enum type to an array
            RoleType[] allRoles = Utils.EnumToArray();

            //Use IEnumerable.Except to get part of the array.
            RoleType[] localUserRoles = new RoleType[] { RoleType.LocalAdmin, RoleType.LocalUser, RoleType.Guest };

            RoleType[] domainUserRoles = allRoles.Except(localUserRoles).ToArray();
        }

        enum RoleType
        {
            DomainAdmin,
            LocalAdmin,
            DomainUser,
            LocalUser,
            Guest
        }
    }
}

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Sorry, the comment form is closed at this time.

©2009 NetInverse. All rights reserved. Powered by WordPress