OrderByDescending C# with Example



OrderByDescending C# with Example

Orders a collection by a specified value. 
When the value is an integer, double or float it starts with the maximal value, which means that you get first the 
positive values, than zero and afterwords the negative values (see Example 1). 
When you order by a char the method compares the ascii values of the chars to sort the collection (see Example 2). 
When you sort strings the OrderBy method compares them by taking a look at their CultureInfo but normaly 
starting with the last letter in the alphabet (z,y,x,...). 
This kind of order is called descending, if you want it the other way round you need ascending (see OrderBy). 
Example 1: 
int[] numbers = {-2, -1, 0, 1, 2}; 
IEnumerable descending = numbers.OrderByDescending(x => x); 
// returns {2, 1, 0, -1, -2} 
Example 2: 
char[] letters = {' ', '!', '?', '[', '{', '+', '1', '9', 'a', 'A', 'b', 'B', 'y', 'Y', 'z', 'Z'}; 
IEnumerable descending = letters.OrderByDescending(x => x); 
// returns { '{', 'z', 'y', 'b', 'a', '[', 'Z', 'Y', 'B', 'A', '?', '9', '1', '+', '!', ' ' } 
Example 3: 
class Person 
{ 
public string Name { get; set; } 
public int Age { get; set; } 
} 
var people = new[] 
{ 
new Person {Name = "Alice", Age = 25}, 
new Person {Name = "Bob", Age = 21}, 
new Person {Name = "Carol", Age = 43} 
}; 
var oldestPerson = people.OrderByDescending(x => x.Age).First(); 
var name = oldestPerson.Name; // Carol 

0 Comment's

Comment Form