Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everyone.
Recently i have encountered with such issue.
In my project i have a list of rooms (simple unordered set).

How can i implement ability of setting order in which this rooms will appears in second page?
Any thoughts?

The firs idea is to create a
C#
Queue<Rooms>
, and perform appropriate actions under it.
But i'm not sure if it's a right way ....
Posted
Updated 14-Aug-12 2:09am
v2

1 solution

To order a Queue:
C#
var rooms = new Queue<Rooms>();

var orderByNumberAsc = rooms.OrderBy(r => r.Number);
var orderByNumberDesc = rooms.OrderByDescending(r => r.Number);


To dynamically order this based on string you need an extension:

C#
public static IQueryable<T> OrderBy<T>(this IQueryable<T> items, string propertyName)
{
    var typeOfT = typeof(T);
    var parameter = Expression.Parameter(typeOfT, "parameter");
    var propertyType = typeOfT.GetProperty(propertyName).PropertyType;
    var propertyAccess = Expression.PropertyOrField(parameter, propertyName);
    var orderExpression = Expression.Lambda(propertyAccess, parameter);

    var expression = Expression.Call(typeof(Queryable), "OrderBy", new[] { typeOfT, propertyType }, items.Expression, Expression.Quote(orderExpression));
    return items.Provider.CreateQuery<T>(expression);
}


Then you can order by a string value:
C#
var rooms = new Queue<Rooms>().AsQueryable();
var orderByNumberAsc = rooms.OrderBy("Number");


And you could easy create an extension for OrderByDescending(string propertyName)

Or a little less dynamic approach using switch statement:
C#
switch (orderByParam)
{
    case "Number":
        rooms = rooms.OrderBy(r => r.Number);
        break;
    case "Capacity":
        rooms = rooms.OrderBy(r => r.Capacity);
        break;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900