2012-06-13 12 views
5

Qualcuno può aiutarmi mostrandomi come ordinare un'espressione LINQ.Come posso ordinare su più campi con LINQ?

Ho il seguente:

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

      }) 

Quello che vorrei fare è quello di fare una sorta sui seguenti punti:

1) primi quattro caratteri o campo RowKey
2) ShortTitle

Non sono sicuro di come fare un ordinamento su pochi caratteri e non sono sicuro di come fare un ordinamento secondario.

+0

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

+0

Utilizzare il ThenBy [Metodo] (http://msdn.microsoft.com/en- us/library/bb535112.aspx). –

+0

possibile duplicato di [Come usare orderby con 2 campi in linq?] (Http://stackoverflow.com/questions/1989674/how-to-use-orderby-with-2-fields-in-linq) – V4Vendetta

risposta

8

Per i primi quattro caratteri, includere che nella sua dichiarazione esistente, quindi aggiungere il ShortTitle poi

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

Ricorda che verrà generata un'eccezione se la lunghezza di item.RowKey è <4 – Tobias

1

È possibile utilizzare 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

Ma io solo ora voglio ordinare i primi quattro caratteri di RowKey. – Alan2

+0

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

1

È possibile utilizzare 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

Per il primo requisito, l'ordinamento per una stringa, è possibile passare Substring nella albero di espressione:

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

(ma essere consapevoli di fuori dai limiti eccezioni .)

Per il tipo secondario, utilizzare the ThenBy() method:

.ThenBy(item => item.ShortTitle) 

Combinato:

.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, 

     }) 
Problemi correlati