

Quite simple but very effective! You can even chain multiple ThenBy() method calls, in case your data is more complex than the data from our test case. List sortedUsers = listOfUsers.OrderBy(user => user.Age).ThenBy(user => user.Name).ToList() Ĭonsole.WriteLine(user.Name + ": " + user.Age + " years") But of course you can get your list of integers and strings sorted easily - that's a piece of cake! However, thanks to LINQ, it's pretty much just as easy to sort more complex objects. We do the exact same thing as before, except that we use the OrderByDescending() method instead of the OrderBy() method. List sortedCityNames = cityNames.OrderByDescending(city => city).ToList() įoreach (string cityName in sortedCityNames) "Amsterdam", "Berlin", "London", "New York" And of course you can do it just as easy with strings, as we'll see in the next example, but let's get the items in descending (from largest to smallest/from Z to A) order: List cityNames = new List()

That was easy, right? Just call the OrderBy() method and supply the object or the member of the object to sort by, and a sorted list will be returned. List sortedNumbers = numbers.OrderBy(number => number).ToList() Fortunately for us, LINQ has several easy-to-use methods for sorting data - let's try a basic example first: List numbers = new List() Therefore, the ability to properly sort the data, once we have the data we need, is crucial. However, as we have previously talked about, your data source for LINQ operations might as well be an XML document or a database. a User class, so the order we got the items in was the same order that they were added to the list. We have used lists of objects, either numeric or based on e.g.
Ef select to new dto with icollections how to#
So, now that we have learned through the previous article how to get data from the data source with LINQ and filter it with the Where() method, the next step could be to sort the data. LINQ: Sorting data: the OrderBy() & ThenBy() methods
