I have a method through an ObjectDataSource feeds a gridview and allows sorting by column using lambda expressions:
public IList<UsersEntity> GetUsers()
{
return new List<UsersEntity>(new[] {
new UsersEntity{ UsrId =1, UsrName="Luis" },
new UsersEntity{ UsrId = 2, UsrName = "Pablo"} });
}
public IList<UsersEntity> GetUsers(string OrderBy)
{
string[] ordParts = OrderBy.Split(' ');
string ordBy = ordParts[0];
string direction = "ASC";
if (2 == ordParts.Length)
direction = "DESC";
//Get Unsorted List
List<UsersEntity> Lista = (List<UsersEntity>)GetUsers();
//Function to order
Func<UsersEntity, object> myFunct = null;
myFunct = (usr) => {
if ("UsrId" == ordBy) return usr.UsrId;
else return usr.UsrName;
};
//sort list
if ("ASC" == direction)
return Lista.OrderBy(myFunct).ToList();
else
return Lista.OrderByDescending(myFunct).ToList();
}
But I want something more functional, something that works for all types of lists and does not involve adding a lot of code. So I wrote this function that I can not complete:
public class OrdenarEntidades<T>
{
public static IEnumerable<T> SortList(IEnumerable<T> Listado, string OrderByArg)
{
string[] arrOrderBy = OrderByArg.Split(' ');
string orderBy = arrOrderBy[0];
string direction = "ASC";
if (2 == arrOrderBy.Length)
direction = "DESC";
foreach (PropertyInfo pInfo in typeof(T).GetProperties())
{
if (orderBy == pInfo.Name)
{
Type tipDev = pInfo.PropertyType;
Func<T, tipDev> MyFunct = (Entity) => { pInfo.GetValue(Entity, null); };
if ("ASC" == direction)
Listado.OrderBy(MyFunct);
else
Listado.OrderBy(MyFunct);
}
}
return Listado;
}
}
I know this code does not compile, however expresses the idea of what I want to accomplish.
Marc Gravell gives an approximation to what I'm looking for (here), but do not know not how to adapt it to my code
Beforehand, thank you very much.