Wednesday, August 19, 2009

The simplest Month generator with c#, linq and anonymous types!

Just come up with a nice solution which i would like to share.

Lets say you want to generate a list of Month names in order to bind them to a DropDownList in an page.

The simplest way i came up with is the following:

DropDownListMonth.DataTextField = "Name";
DropDownListMonth.DataValueField = "Number";
DropDownListMonth.DataSource = Numbers(1,12).Select(Number=> new 
    Name = (new DateTime(2000,Number,1)).ToString("MMMM")

public static IEnumerable<int> Numbers(int from, int to)
    for (int i = from; i <= to; i++)
        yield return i;

So, Linq and anonymous types rocks!