Return to Snippet

Revision: 31874
at September 15, 2010 02:32 by jermeyz

Initial Code
/// <summary>
        /// Converts an IEnumberable to a list of SelectListItems
        /// </summary>
        /// <typeparam name="T">Type of items in data</typeparam>

        /// <typeparam name="TValueType">Type of property to be used for the Value property</typeparam>
        /// <typeparam name="TTextType">Type of property to be used for the Textproperty</typeparam>
        /// <param name="data">List to convert</param>
        /// <param name="defaultItem">An optional extra listItem appeneded at the beginning of the list</param>
        /// <param name="valueProperty">property of T to be used for the Value property</param>
        /// <param name="textProperty">property of T to be used for the Text property</param>
        /// <param name="selectedValue">Item in return value that should be selected</param>
        /// <returns></returns>
        public static List<SelectListItem> ToSelectList<T, TValueType, TTextType>(IEnumerable<T> data, SelectListItem defaultItem, Expression<Func<T, TValueType>> valueProperty, Expression<Func<T, TTextType>> textProperty, string selectedValue)
            var list = new List<SelectListItem>();

            if (defaultItem != null)
            if (data == null)
                return list;

            var memberInfo = textProperty.Body as MemberExpression;
            var textPropName = memberInfo.Member.Name;

            var valmemberInfo = valueProperty.Body as MemberExpression;
            var valuePropName = valmemberInfo.Member.Name;

            Type t = typeof(T);

            var textProp = t.GetProperties().Where(prop => prop.Name == textPropName).Single();
            var valueProp = t.GetProperties().Where(prop => prop.Name == valuePropName).Single();

            foreach (var item in data)

                var text = textProp.GetValue(item, null);
                var value = valueProp.GetValue(item, null);

                list.Add(new SelectListItem()
                    Text = text.ToString(),
                    Value = value.ToString(),
                    Selected = (selectedValue == value.ToString())

            return list;

Initial URL

Initial Description

Initial Title
Generic List bind to a drop down

Initial Tags
dropdown, c

Initial Language