2009-02-17

Linq 基本語法 – OrderBy 與 OrderByDescending

這兩個使用方式都相當簡單

OrderBy:
The OrderBy operator allows an input sequence to be ordered based on a keySelector method that will return a key value for each input element, and an ordered output sequence, IOrderedEnumerable<T>, will be yielded in ascending order based on the values of the returned keys.

若繼續範例中的那個字串陣列

var nameObjs = presidents.OrderBy(s=>s);
StringBuilder sb = new StringBuilder();
 
foreach (var item in nameObjs)
{
  sb.AppendLine(item);                
}
richTextBox1.Text = sb.ToString();


可以得到如下結果:
 
image

OrderByDescending:
This operator is prototyped and behaves just like the OrderBy operator, except that it orders in descending order.

從上面的字義,可以很清楚了解到
其實OrderByDescending是降冪排序
而OrderBy是升冪排序

var nameObjs = presidents.OrderByDescending(s=>s);
StringBuilder sb = new StringBuilder();
 
foreach (var item in nameObjs)
{
  sb.AppendLine(item);                
}
 
richTextBox1.Text = sb.ToString();


最後產生如下結果:   
image

沒有留言:

張貼留言