I have IEnumerable<Cars>
variable to which I'm assigning values from the database.
I would like to apply sorting based on the user's input to the above variable.
I have columns like in the UI i.e. Car Model, Car Model's year, Number of car sold out, Number of car in stock. I have implemented multiple sorting on the table means user can select a column and based on that he can sort the other column.
In this case, if user selects Car Model in ascending order and he will get the results based on the selection and now when he selects the next column i.e year, the previous order shouldn't change.
It is kind of Orderby().ThenBy()
;
I have foreach in which I have implemented switch case
switch(field) //field prop will come from foreach
{
case "CarModel":
objCars = sortMember.Dir.ToUpperInvariant() == "ASC" ?
objCars.OrderBy(x => x.CarModel).ToList() :
objCars.OrderByDescending(x => x.CarModel).ToList();
break;
case "CarYear":
objCars = sortMember.Dir.ToUpperInvariant() == "ASC" ?
objCars.OrderBy(x => x.CarYear).ToList() :
objCars.OrderByDescending(x => x.CarYear).ToList();
break;
}
I also tried to implement using IOrderedEnumerable
. During debugging I found that sorting is happening based on the input when we IOrderedEnumberable
but finally when I'm assigning back to the IEnumerable
variable, I'm losing the order.
Assuming user selects the 'Car Model column' as the first sorting item,
switch(field)
{
case "CarModel":
objCars_Sorted = sortMember.Dir.ToUpperInvariant() == "ASC" ?
objCars.OrderBy(x => x.CarModel).ToList() :
objCars.OrderByDescending(x => x.CarModel).ToList();
break;
case "CarYear":
objCars_Sorted = sortMember.Dir.ToUpperInvariant() == "ASC" ?
objCars_Sorted.OrderBy(x => x.CarYear).ToList() :
objCars_Sorted.OrderByDescending(x => x.CarYear).ToList();
break;
}
objCars = objCars_Sorted.Skip(0).Take(10).Tolist() //I also tried objCars_Sorted.AsEnumerable but no luck
Above code return without the expected sorting i.e.
OrderBy(CarModel).ThenBy(CarYear).
Is there any other way or any change needs to be done on my code above?
Please suggest.