Pindakaas
Pindakaas

Reputation: 4439

create sort on list for web API controller

I am writing my first web API controller so I am a bit of a noob in this area. I am trying to retrieve a list of data through a static class called CustomerDataSource:

public static class CustomerDataSource
{
    public static List<Customer> customerData
    {
        get
        {
            Customer customer1 = new Customer() { name = "Bert", address = "London" };
            Customer customer2 = new Customer() { name = "Jon", address = "New York" };
            List<Customer> listCustomers = new List<Customer>();
            listCustomers.Add(customer1);
            listCustomers.Add(customer2);
            return listCustomers;
        }
    }
}

public class Customer
{
    public string name { get; set; }
    public string address { get; set; }
}

I am a bit stuck with my ApiController because I am trying to sort the list either on 'name' or 'address' but using a string called 'field' does not compile. What would be a good implementation for a WebAPI controller GETmethod which provides for sorting on one of the Customer properties ?

public class ValuesController : ApiController
{
    // GET api/values
    public List<Customer> Get(string field)
    {
        var list = CustomerDataSource.customerData.OrderBy(field);
    }
}

Upvotes: 3

Views: 7516

Answers (2)

Lin
Lin

Reputation: 15188

Create an extension method like below, then you can use it anywhere within the same namespace in your project.

public static class extensionmethods
    {
        public static IQueryable<T> OrderByPropertyName<T>(this IQueryable<T> q, string SortField, bool Ascending)
        {
            var param = Expression.Parameter(typeof(T), "p");
            var prop = Expression.Property(param, SortField);
            var exp = Expression.Lambda(prop, param);
            string method = Ascending ? "OrderBy" : "OrderByDescending";
            Type[] types = new Type[] { q.ElementType, exp.Body.Type };
            var rs = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
            return q.Provider.CreateQuery<T>(rs);
        }
    }

Then you can use it like:

 public List<Customer> Get(string PropertyName)
    {
        var list = CustomerDataSource.customerData.AsQueryable().OrderByPropertyName("PropertyName",true).ToList();
    }

Note: Because the extension method uses IQueryable and returns IQuerybale, so you need to convert your List to IQueryable. Also you can order the list by ascending and descending order, just pass the boolean type value to the second parameter. The default is ascending.

Upvotes: 8

aw04
aw04

Reputation: 11187

You need to use a lambda expression.

if (field == "name")
    var list = CustomerDataSource.customerData.OrderBy(d => d.name);
else if (field == "address")
    var list = CustomerDataSource.customerData.OrderBy(d => d.address);

Upvotes: 4

Related Questions