C# Language Ordre des requêtes - OrderBy () ThenBy () OrderByDescending () ThenByDescending ()


Exemple

string[] names= { "mark", "steve", "adam" };

Ascendant:

Syntaxe de requête

var sortedNames =
    from name in names
    orderby name
    select name;

Syntaxe de la méthode

var sortedNames = names.OrderBy(name => name);

namedNames contient les noms dans l'ordre suivant: "adam", "mark", "steve"

Descendant:

Syntaxe de requête

var sortedNames =
    from name in names
    orderby name descending
    select name;

Syntaxe de la méthode

var sortedNames = names.OrderByDescending(name => name);

namedNames contient les noms dans l'ordre suivant: "steve", "mark", "adam"

Commander par plusieurs champs

Person[] people =
{
    new Person { FirstName = "Steve", LastName = "Collins", Age = 30},
    new Person { FirstName = "Phil" , LastName = "Collins", Age = 28},
    new Person { FirstName = "Adam" , LastName = "Ackerman", Age = 29},
    new Person { FirstName = "Adam" , LastName = "Ackerman", Age = 15}
};

Syntaxe de requête

var sortedPeople = from person in people
                   orderby person.LastName, person.FirstName, person.Age descending
                   select person;

Syntaxe de la méthode

 sortedPeople = people.OrderBy(person => person.LastName)
                      .ThenBy(person => person.FirstName)
                      .ThenByDescending(person => person.Age);

Résultat

1. Adam Ackerman 29
2. Adam Ackerman 15
3. Phil Collins  28
4. Steve Collins 30