LINQ Queries with dynamic Order By

前端 未结 3 2152
一个人的身影
一个人的身影 2021-02-14 19:44

I have a query where I need to have ordeby based on a querystring parameter .For example if sortby parameter is price , Query needs to change with price . If its rating than cha

3条回答
  •  [愿得一人]
    2021-02-14 20:25

    Well, you could use a switch statement or something similar:

    IQueryable query = ...;
    
    switch (orderByParameter)
    {
        case "price":
            query = query.OrderBy(x => x.Price);
            break;
        case "rating":
            query = query.OrderBy(x => x.Rating);
            break;
        // etc
    }
    

    You could also do it with reflection, but assuming you have a limited number of fields to order by, this is quite possibly the simplest approach.

提交回复
热议问题