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);
- }
- }
Thus, the coding is self explanatory.
Now, let's look at an example, which uses this piece of coding.
The model is shown below.
- public class ClassModel
- {
- public string ClassName { get; set; }
- public List<StudentModel> students
- {
- get
- {
- return new List<StudentModel>()
- {
- new StudentModel()
- {
- StudentId = 1,
- Name = "Name1",
- Mark1 = 74.50M
- },
- new StudentModel()
- {
- StudentId = 2,
- Name = "Name2",
- Mark1 = 63.00M
- },
- new StudentModel()
- {
- StudentId = 3,
- Name = "Name3",
- Mark1 = 87.00M
- },
- new StudentModel()
- {
- StudentId = 4,
- Name = "Name4",
- Mark1 = 81.00M
- }
- };
- }
- }
- }
-
- public class StudentModel
- {
- public int StudentId { get; set; }
- public string Name { get; set; }
- public decimal Mark1 { get; set; }
- }
The coding, shown below, uses the method which we created.
- ClassModel cm = new ClassModel();
- List<SelectListItem> selLstitem = cm.students.GetSelectListItem("Name", "StudentId");