Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
XML
Enum.GetValues(typeof(Gender)).Cast<Gender>().Select(c => new SelectListItem {
 Text = c.ToString(),
 Value = c.ToString()
}));


Here Gender is an Enum.

Please explain me what is this statement doing with each step by step.

Thanks
Posted
Comments
[no name] 4-Dec-14 10:21am    
This converts a enumeration by casting it to the Type gender to a List of or a single SelectListItem.

1 solution

Once you remove the final close bracket to get it to compile...

Enum.GetValues returns an array of the values in the enum: so if teh enum was:
C#
public enum Gender
    {
    Male = 1,
    Female = 2,
    Bieber = 666,
    }
Then it would return an array of three integer values: 1, 2, 666
These it then casts to an IEnumerable of Gender class items, and uses Select to convert each of those into a new SelectListItem instance and finally results in an IEnumerable of those.
It's the equivalent of this code:
C#
List<SelectListItem> list = new List<SelectListItem>();
foreach (int i in Enum.GetValues(typeof(Gender)))
    {
    Gender g = (Gender)i;
    SelectListItem item = new SelectListItem();
    item.Text = g.ToString();
    item.Value = g.ToString();
    list.Add(item);
    }
IEnumerable<SelectListItem> returnValue = list;
 
Share this answer
 
Comments
Sumit Bhargav 4-Dec-14 10:47am    
Thanks,
That's what i needed to know.
OriginalGriff 4-Dec-14 10:54am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900