I have a bit of a challenge. I need to sort a List of objects, and I need to sort it from a string representing the path to the property in any sub class. I need to use the List.Sort() and not OrderBy().
Lest make a simple example. I have a list of persons represented by two sub classes for identification and name
public class NameParts
{
public String FirstName { get; set; }
public String LastName { get; set; }
}
public class Identification
{
public String NiNumber { get; set; }
public NameParts Name { get; set; }
}
public class Person
{
public String Email { get; set; }
public String Phone { get; set; }
public Int16 Age { get; set; }
public Identification Id { get; set; }
}
Now I need to sort the list by age. Very simple
public static void SortByAge(List<Person> listToSort)
{
listToSort.Sort((x, y) => x.Age.CompareTo(y.Age));
}
And even by NiNumber and FirstName it is fairly simple this way
public static void SortByNiNumber(List<Person> listToSort)
{
listToSort.Sort((x, y) => x.Id.NiNumber.CompareTo(y.Id.NiNumber));
}
public static void SortByFirstName(List<Person> listToSort)
{
listToSort.Sort((x, y) => x.Id.Name.FirstName.CompareTo(y.Id.Name.FirstName));
}
Now comes the tricky part. I need to perform all the above sorts giving a string that represents the path to theproperty to sort by. Like "Id.Name.FirstName"
So I need
public static void SortByAny(List<Person> listToSort, String sortBy)
{
//??????
}
That can be called with
List<Person> theList = new List<Person>();
SortByAny(theList, "Age");
SortByAny(theList, "Id.NiNumber");
SortByAny(theList, "Id.Name.FirstName");
I know I need to use reflection for this, and I have managed to do so but I cannot get further than properties in the Person Class itself, so I probably need to do something else, and this is where I'm stuck.
Does anyone have some brilliant ideas on how to solve this?
Thanks
Aucun commentaire:
Enregistrer un commentaire