Pin*_*aas 2 c#-4.0 asp.net-web-api
我正在编写我的第一个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; }
}
Run Code Online (Sandbox Code Playgroud)
我对我的ApiController有点困惑,因为我试图在'name'或'address'上对列表进行排序,但使用名为'field'的字符串不能编译.对于WebAPI控制器GETmethod来说,什么是一个很好的实现,它提供了对其中一个Customer属性的排序?
public class ValuesController : ApiController
{
// GET api/values
public List<Customer> Get(string field)
{
var list = CustomerDataSource.customerData.OrderBy(field);
}
}
Run Code Online (Sandbox Code Playgroud)
创建如下所示的扩展方法,然后您可以在项目的同一命名空间内的任何位置使用它.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用它:
public List<Customer> Get(string PropertyName)
{
var list = CustomerDataSource.customerData.AsQueryable().OrderByPropertyName("PropertyName",true).ToList();
}
Run Code Online (Sandbox Code Playgroud)
注意:因为扩展方法使用IQueryable并返回IQuerybale,所以您需要将List转换为IQueryable.您也可以按升序和降序对列表进行排序,只需将布尔类型值传递给第二个参数即可.默认为升序.
| 归档时间: |
|
| 查看次数: |
4162 次 |
| 最近记录: |