Content feed Comments Feed

The Official ASATO Site

Hi, welcome to my blog. ASP,asp.net,Health,Javascript,JQUERY

Convert Enum to List

Posted by admin On March - 22 - 2010

An enumeration is a named constant whose underlying type is any integral type except Char. If no underlying type is explicitly declared, Int32 is used. Programming languages typically provide syntax to declare an enumeration that consists of a set of named constants and their values.
example1:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
enum class Colors
{
   public enum SetType {
   	Red = 1,
   	Green = 2,
   	Blue = 4,
   	Yellow = 8
   }
};

We can get value from this enum:

?View Code CSHARP
1
Console.WriteLine(Colors.Green.ToString());

We can takes an enum type and returns a generic list populated with each enum item.
first,we write a class name

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
namespace wind-flowers.Core {
    [Serializable]
    public class SetCollections {
        public SetCollections() { }
        public SetCollections(string id) {
            this._id = id;
        }
        public SetCollections(string id, string title) {
            this._id = id;
            this._title = title;
        }
 
        private string _id;
        public string Id {
            get { return _id; }
            set { _id = value; }
        }
        private string _title;
        public string Title {
            get { return _title; }
            set { _title = value; }
        }
    }
}

then , we can get a List from enum Colors:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
	public  List<SetCollections> SetList() {
            List<SetCollections> List = new List<SetCollections>();
            String[] EnumTypes = Enum.GetNames(typeof(Colors.SetType));
            foreach (int i in Enum.GetValues(typeof(Colors.SetType))) {
                SetCollections collecte = new SetCollections(
                        i.ToString(), 
                        Enum.GetName(typeof(Colors.SetType), i),
                        getItems(i.ToString())
                    );
                List.Add(collecte);
            }
            return List;
        }