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>
  1. public static class ExtensionMethodClasses
  2. {
  3. public static List<SelectListItem> GetSelectListItem<T>(this List<T> lstValues, string PropertyText, string PropertyValue)
  4. {
  5. List<SelectListItem> lstSelectListItem = new List<SelectListItem>();
  6. SelectListItem selLstItem;
  7. foreach(T t in lstValues)
  8. {
  9. selLstItem = new SelectListItem()
  10. {
  11. Text = GetPropValue(t, PropertyText).ToString(),
  12. Value = GetPropValue(t, PropertyValue).ToString()
  13. };
  14. lstSelectListItem.Add(selLstItem);
  15. }
  16. return lstSelectListItem;
  17. }
  18. public static object GetPropValue(object src, string propName)
  19. {
  20. return src.GetType().GetProperty(propName).GetValue(src, null);
  21. }
  22. }
Thus, the coding is self explanatory.
Now, let's look at an example, which uses this piece of coding.
The model is shown below.
  1. public class ClassModel
  2. {
  3. public string ClassName { get; set; }
  4. public List<StudentModel> students
  5. {
  6. get
  7. {
  8. return new List<StudentModel>()
  9. {
  10. new StudentModel()
  11. {
  12. StudentId = 1,
  13. Name = "Name1",
  14. Mark1 = 74.50M
  15. },
  16. new StudentModel()
  17. {
  18. StudentId = 2,
  19. Name = "Name2",
  20. Mark1 = 63.00M
  21. },
  22. new StudentModel()
  23. {
  24. StudentId = 3,
  25. Name = "Name3",
  26. Mark1 = 87.00M
  27. },
  28. new StudentModel()
  29. {
  30. StudentId = 4,
  31. Name = "Name4",
  32. Mark1 = 81.00M
  33. }
  34. };
  35. }
  36. }
  37. }
  38. public class StudentModel
  39. {
  40. public int StudentId { get; set; }
  41. public string Name { get; set; }
  42. public decimal Mark1 { get; set; }
  43. }
The coding, shown below, uses the method which we created.
  1. ClassModel cm = new ClassModel();
  2. List<SelectListItem> selLstitem = cm.students.GetSelectListItem("Name", "StudentId");