LINQ Queries with dynamic Order By

前端 未结 3 1791
长发绾君心
长发绾君心 2021-02-14 19:41

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:27

    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.

提交回复
热议问题