2012-06-13 17 views
5

¿Alguien me puede ayudar mostrándome cómo ordenar una expresión LINQ?¿Cómo puedo ordenar múltiples campos con LINQ?

Tengo el siguiente:

.OrderByDescending(item => item.RowKey) 
.Select((t, index) => new City.Grid() 
      { 
       PartitionKey = t.PartitionKey, 
       RowKey = t.RowKey, 
       Row = index + 1, 
       ShortTitle = t.ShortTitle, 

      }) 

Lo que me gustaría hacer es hacer una especie de lo siguiente:

1) Las primeras cuatro caracteres o rowKey campo
2) ShortTitle

No estoy seguro de cómo hacer una clasificación con solo unos pocos caracteres y tampoco estoy seguro de cómo hacer una clasificación secundaria.

+0

tratar .OrderByDescending (item => {item.RowKey, item.ShortTitle}) –

+0

Uso del ThenBy [método] (http://msdn.microsoft.com/en- us/library/bb535112.aspx). –

+0

posible duplicado de [¿Cómo usar orderby con 2 campos en linq?] (Http://stackoverflow.com/questions/1989674/how-to-use-orderby-with-2-fields-in-linq) – V4Vendetta

Respuesta

8

Durante los primeros cuatro caracteres, que incluyen en su estado de cuenta existente, a continuación, añadir la ShortTitle después

.OrderByDescending(item => item.RowKey.Substring(0,4)) 
.ThenBy(item => item.ShortTitle) 
+0

Tenga en cuenta que se lanzará una excepción si la longitud del elemento.RowKey es <4 – Tobias

1

Puede utilizar OrderByDescending (...). ThenBy() ...

.OrderByDescending(item => item.RowKey.Substring(0, Math.Min(4, item.RowKey.Length))) 
.ThenBy(item => item.ShortTitle) 
.Select((t, index) => new City.Grid() 
     { 
      PartitionKey = t.PartitionKey, 
      RowKey = t.RowKey, 
      Row = index + 1, 
      ShortTitle = t.ShortTitle, 

     }) 

HTH Tobi

+0

Pero yo solo ahora quiero ordenar los primeros cuatro caracteres de RowKey. – Alan2

+0

item.Rowkey.Substring (0, Math.Min (4, item.RowKey.Length)) – Tobias

1

Puede utilizar Enumerable.ThenBy method

.OrderByDescending(item => item.RowKey) 
.ThenByDescending(item => item.ShortTitle) 
.Select((t, index) => new City.Grid() 
      { 
       PartitionKey = t.PartitionKey, 
       RowKey = t.RowKey, 
       Row = index + 1, 
       ShortTitle = t.ShortTitle, 

      }) 
1

Para el primer requisito, la clasificación por una subcadena, puede pasar Substring en el árbol de expresión:

.OrderByDescending(item => item.RowKey.Substring(0, 4)) 

(Pero ser consciente de fuera de límites excepciones .)

Para la clase secundaria, use the ThenBy() method:

.ThenBy(item => item.ShortTitle) 

combinado:

.OrderByDescending(item => item.RowKey.Substring(0, 4)) 
.ThenBy(item => item.ShortTitle) 
.Select((t, index) => new City.Grid() 
     { 
      PartitionKey = t.PartitionKey, 
      RowKey = t.RowKey, 
      Row = index + 1, 
      ShortTitle = t.ShortTitle, 

     }) 
Cuestiones relacionadas