I have several Lists<> that holds objects of different classes.
List<classA> listA;
List<classB> listB;
List<classC> listC;
//...
List<classM> listM;
The classes do not relate in any way and have nothing in common except that they might have a single property marked with an Attribute SortBy=true
[CustomObjectComparerAttribute(IncludeInCompare = true, Title = "View Order", SortBy=true)]
public int ViewOrder { get; set; }
What I would like to do is to have a generic function that accepts a list of any sort. This is problem Nr 1, because I can not figure out a way to make a function accept Lists<> of different types.
private List<object> SortList(List<object> aList) //<-- this is not allowed (problem 1)
{
//Get which property we sort by...
PropertyInfo prop = GetPropertyToSortBy(objectA);
//Sort the list
//Problem Nr 2: How do I get `PropertyInfo prop` in the statement below
List<Order> SortedList = aList.OrderBy(o=>o.ThePropToSortBy).ToList();
}
private PropertyInfo GetPropertyToSortBy(object o)
{
Type t = o.GetType();
foreach (PropertyInfo prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (Attribute.IsDefined(prop, typeof(CustomObjectComparerAttribute)) && ((CustomObjectComparerAttribute)Attribute.GetCustomAttribute(prop, typeof(CustomObjectComparerAttribute))).SortBy == true)
{
return prop;
}
}
return null;
}
I feel that Im attacking this problem from the wrong angle. Am I on the right track?, and if so, how can I solve my problems?
if not, can you point me in the right direction?
IComparable
?IComparable<T>
on each type, you can useList<T>.Sort()
.