This post, just like the code example, is short and to the point, because that’s how LINQ is – short, to the point, and powerful.
Let’s say you have an object called Country. There will be a List<> populated with it that is going to be used in a drop-down box. It has the following properties:
- CountryName (string)
- DropDownValue (string)
- SortOrder (int)
The business logic for the list is to order it by SortOrder, and then by CountryName. You ready for the code?
var destinationList = sourceList.OrderBy(c => c.SortOrder).ThenBy(c=> c.CountryName).ToList();
That’s it. You should note that the difference between OrderBy() and Sort() is that Sort() will actually resort the list you are running it on. OrderBy() on the other hand just returns the result set, but doesn’t actually commit the order to the list; hence, the ToList() assignment to destinationList.