我有一个类型对象列表 }
我需要对
列表进行排序我可以动态地执行此操作吗。
请帮忙。
答案 0 :(得分:2)
LINQ有OrderBy / OrderByDescending个方法,这使得这种类型的排序变得微不足道。例如
var orderByBookingRef = listOfRestaurants.OrderBy(x => x.Booking.BookingRef);
var orderByLatestBooking = listOfRestaurants.OrderByDescending(x => x.Booking.BookingDateTime);
var orderByLatestReview = listOfRestaurants.OrderByDescending(x => x.RestReview.ReviewDate);
以上称为 Lambda 表达式,如果您更喜欢纯LINQ语法,则在可读性方面要好一些
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;
答案 1 :(得分:0)
另一种形式的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;
具体情况,假设您的列表名为MyList
,请Restaurant.RestaurantId
字段:
var sorted_list =
from rest in MyList
orderby rest.Restaurant.RestaurantId
select rest;
将按餐厅的ID返回列表,升序
根据评论:你可以做到
var sorted_list =
from rest in MyList
where rest.Booking != null && // same for the rest
orderby rest.Restaurant.RestaurantId
select rest;
这样它就会跳过那些空的......