I have a C# custom object collection which has a property name ISBN. I also have a variable which has some but not all of the ISBN's in the form of List. I want to order the custom object collection such that those usernames in the List are listed first followed by others. I did something like the following:
var allBooks = GetAllBooks();
//First show the books popular among your friends followed by others from isbnList.
var priorityList = allBooks.Where(p => isbnList.Contains(p.ISBN)).ToList();
var otherList = allBooks.Where(p => !isbnList.Contains(p.ISBN)).ToList();
priorityList.AddRange(otherList);
return priorityList;
Essentially first I am getting subset of the object list corresponding to List followed by the rest. Then I am combining both the list and return the entire list. I am not sure whether this is the correct way of doing it or not. Also, I am not sure, once combined, will it retain the order in which the items were added or it will create its own order.
Thanks
You can use OrderBy(Descending)
/ ThenBy(Descending)
with bool
. false
will be before true
, so to get correct order you need OrderByDescending
:
var allBooks = GetAllBooks();
//First show the books popular among your friends followed by others from isbnList.
var priorityList = allBooks.OrderByDescending(p => isbnList.Contains(p.ISBN)).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.