Fun with LINQ

2009 October 20
tags: , ,
by Nick Lamb

I’m working on a form that needs three dropdowns for a user to input a date like this:

Rather than get out my ctrl+c, ctrl+v skills, I thought it’d be fun to play with LINQ in C#. First off, I’ll say that I know this is not the most efficient code, yes I know there’s hidden loops when it calls ToList() and Enumerable.Range() I was going for very succinct code that looked pretty, not performance.

The thing that makes this so nice is Enumerable.Range(int start, int count); This gets a continuous range of numbers with very little typing. And with each of those numbers just select a new ListItem. Another nice thing is to have quick ordering capabilities. I needed only the last 5 years from this year in descending order, that was easy with LINQ too. Once all the ListItems are created, it’s just a matter of converting the IEnumerable to an IList so we can call ForEach on it to add items to the dropdown all in one line of code.

        protected void LoadDateDropdowns()
        {
            var months = from i in Enumerable.Range(1, 12)
                         select new ListItem()
                         {
                             Text = new DateTime(1900, i, 1).ToString("MMMM"),
                             Value = new DateTime(1900, i, 1).ToString("MMMM")
                         };

            var days = from i in Enumerable.Range(1, 31)
                       select new ListItem()
                       {
                           Text = i.ToString(),
                           Value = i.ToString()
                       };

            var years = from i in Enumerable.Range(DateTime.Now.Year - 5, 5)
                        orderby i descending
                        select new ListItem()
                        {
                            Text = i.ToString(),
                            Value = i.ToString()
                        };

            // add the months to the dropdown
            months.ToList().ForEach(i => ddlManufactureMonth.Items.Add(i));

            // add the days to the dropdown
            days.ToList().ForEach(i => ddlManufactureDay.Items.Add(i));

            // add the years to the dropdown
            years.ToList().ForEach(i => ddlManufactureYear.Items.Add(i));
        }
  • abigail daniel

    I don’t get your point!