Reflection, Generics, and Extension methods are powerful features but with a little lateral thinking, these can be combined and we can find interesting solutions for problems.
Thus, I am here with an interesting piece of code, which combines all the features, mentioned above.
While doing coding, we often have to fill List<SelectListItem>. We have to take values from List<T>, extract the values from the selected properties and fill the List<SelectListItem>.
The objective of the piece of coding shown below is to write an extended generic method, which takes a List<T> as an input parameter and also has two more strings, which are property names of the classes and returns List<SelectListItem>
- public static class ExtensionMethodClasses
- {
- public static List<SelectListItem> GetSelectListItem<T>(this List<T> lstValues, string PropertyText, string PropertyValue)
- {
- List<SelectListItem> lstSelectListItem = new List<SelectListItem>();
- SelectListItem selLstItem;
- foreach(T t in lstValues)
- {
- selLstItem = new SelectListItem()
- {
- Text = GetPropValue(t, PropertyText).ToString(),
- Value = GetPropValue(t, PropertyValue).ToString()
- };
- lstSelectListItem.Add(selLstItem);
- }
- return lstSelectListItem;
- }
- public static object GetPropValue(object src, string propName)
- {
- return src.GetType().GetProperty(propName).GetValue(src, null);
- }
- }
Now, let's look at an example, which uses this piece of coding.
The model is shown below.

Join the conversation! Your thoughts help the community grow.