Reputation: 77
I have a list of objects of type }
I need to sort the list of
Can I do this dynamically.
Please help.
Upvotes: 1
Views: 157
Reputation: 11783
And the other form of linq:
var sorted_by_prop =
from some_object in list_of_rest
orderby some_object.prop_name_here descending // or ignore descending if you don't want it descending
select some_object;
Specific case, assuming your list is called MyList
, by Restaurant.RestaurantId
field:
var sorted_list =
from rest in MyList
orderby rest.Restaurant.RestaurantId
select rest;
Will return the list by the Id of the restaurant, ascending
As per comment: You can do
var sorted_list =
from rest in MyList
where rest.Booking != null && // same for the rest
orderby rest.Restaurant.RestaurantId
select rest;
this way it'll skip the ones that are null ...
Upvotes: 0
Reputation: 82136
LINQ has OrderBy / OrderByDescending methods which make this type of sorting trivial e.g.
var orderByBookingRef = listOfRestaurants.OrderBy(x => x.Booking.BookingRef);
var orderByLatestBooking = listOfRestaurants.OrderByDescending(x => x.Booking.BookingDateTime);
var orderByLatestReview = listOfRestaurants.OrderByDescending(x => x.RestReview.ReviewDate);
The above is known as Lambda expressions which are a bit better in terms of readability, if you prefer pure LINQ syntax
var orderByBookingRef = from r in listOfRestaurants
orderby r.Booking.BookingRef
select r;
var orderByLatestBooking = from r in listOfRestaurants
orderby r.Booking.BookingDateTime descending
select r;
var orderByLatestReview = from r in listOfRestaurants
orderby r.RestReview.ReviewDate descending
select r;
Upvotes: 2