我正在编写我的第一个Web API控制器,所以我在这方面有点像菜鸟。我试图通过名为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; }
}
我对ApiController有点困惑,因为我试图在'name'或'address'上对列表进行排序,但使用名为'field'的字符串不能编译。什么是WebAPI控制器GET方法的良好实现,它提供了对其中一个Customer属性的排序?
public class ValuesController : ApiController
{
// GET api/values
public List<Customer> Get(string field)
{
var list = CustomerDataSource.customerData.OrderBy(field);
}
}
答案 0 :(得分:8)
创建如下所示的扩展方法,然后您可以在项目的同一命名空间内的任何位置使用它。
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);
}
}
然后你就可以使用它:
public List<Customer> Get(string PropertyName)
{
var list = CustomerDataSource.customerData.AsQueryable().OrderByPropertyName("PropertyName",true).ToList();
}
注意: 因为扩展方法使用IQueryable并返回IQuerybale,所以您需要将List转换为IQueryable。您也可以按升序和降序对列表进行排序,只需将布尔类型值传递给第二个参数即可。默认值为升序。
答案 1 :(得分:4)
您需要使用lambda表达式。
if (field == "name")
var list = CustomerDataSource.customerData.OrderBy(d => d.name);
else if (field == "address")
var list = CustomerDataSource.customerData.OrderBy(d => d.address);