LINQ OrderBy con más de un campo


Tengo una lista que necesito ordenada por dos campos. He intentado usar OrderBy en LINQ, pero eso solo me permite especificar un campo. Estoy buscando que la lista se ordene por el primer campo y luego si hay duplicados en el primer campo para ordenar por el segundo campo.

Por ejemplo, quiero que los resultados se vean así (ordenados por apellido y luego por nombre).

  • Adams, John
  • [6] Smith, James {[7]]}
  • Smith, Peter
  • [6] Thompson, Fred

He visto que puedes usar la sintaxis SQL para lograr esto pero estoy buscando una manera de hacerlo con el método OrderBy.

IList<Person> listOfPeople = /*The list is filled somehow.*/
IEnumerable<Person> sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName, aPerson.FirstName); //This doesn't work.
 67
Author: Community, 2010-06-15

6 answers

Necesita usar ThenBy:

listOfPeople.OrderBy(person => person.LastName)
            .ThenBy(person => person.FirstName)
 135
Author: tzaman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-15 17:31:10

Si desea utilizar la sintaxis del método, utilice ThenBy(), como otros sugirieron:

listOfPeople.OrderBy(person => person.LastName)
            .ThenBy(person => person.FirstName)

En la sintaxis de consulta, lo mismo se puede lograr prácticamente de la manera que usted quería: dos claves de ordenación separadas por una coma:

from person in listOfPeople
orderby person.LastName, person.FirstName
select person

El código anterior será realmente compilado a código que usa OrderBy() y ThenBy(), como en el primer ejemplo.

También, si desea tener OrderBy() que toma dos (o más) claves de ordenación, ciertamente puede escribir eso como un método de extensión en IEnumerable<T> que internamente llamadas OrderBy() y ThenBy().

 21
Author: svick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-08 21:21:36

Sus campos posteriores deben ser ordenados usando el método ThenBy ()

 2
Author: Ben Robinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-15 17:25:53

Use .ThenBy(aPerson=>field2);

 1
Author: Robaticus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-15 17:24:59
var sortedListOfPeople = listOfPeople.OrderBy(aPerson => aPerson.LastName).ThenBy(a => aPerson.FirstName);
 1
Author: moi_meme,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-15 17:25:30

La forma de ordenar una lista con más archivos es la siguiente:

var soterdList = initialList.OrderBy(x => x.Priority).
                                    ThenBy(x => x.ArrivalDate).
                                    ThenBy(x => x.ShipDate);

Puede agregar otros campos con clasole "ThenBy"

 0
Author: daniele3004,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-20 12:31:01