通過orderby關鍵字,LINQ可以實現升序和降序排序。LINQ還支持次要排序。


通過orderby關鍵字,LINQ可以實現升序和降序排序。LINQ還支持次要排序。

LINQ默認的排序是升序排序,如果你想使用降序排序,就要使用descending關鍵字。

static void Main(string[] args)
{
    var dicts = new Dictionary<int, string>();
 
    dicts.Add(9, "Jack");
    dicts.Add(13, "Tom");
    dicts.Add(5, "Tod");
    dicts.Add(2, "Alics");
 
    var dictSorted = from n in dicts
                     orderby n.Key descending
                     select n;
 
    foreach (var item in dictSorted)
    {
        Console.WriteLine(item.Value);
    }
    /*Output
     * Tom
     * Jack
     * Tod
     * Alics
     */
}

 

以上的示例也可以直接使用擴展方法來達到相同的效果:

static void Main(string[] args)
{
    var dicts = new Dictionary<int, string>();
 
    dicts.Add(9, "Jack");
    dicts.Add(13, "Tom");
    dicts.Add(5, "Tod");
    dicts.Add(2, "Alics");
 
    foreach (var item in dicts.OrderByDescending(n=>n.Value))
    {
        Console.WriteLine(item.Value);
    }
}

 

輸出結果跟上述示例是相同的。

LINQ的任何功能都是構建在擴展方法之上的,但有些功能擁有LINQ關鍵字,有些又只能通過擴展方法實現。比如Reverse擴展方法可以翻轉集合中的元素,但並沒有提供相應的LINQ關鍵字,所以只能通過擴展方法的方式調用。

關於排序的擴展方法有OrderBy、OrderByDescending、ThenBy、ThenByDescending和Reverse。很多LINQ的關鍵字和它們的擴展方法名對應,有些則是隱含的,比如你加上Descending的關鍵字,就會調用mathodnameByDescending的擴展方法。

下面的示例來說明一下次要排序。從擴展方法的角度講就是調用ThenBy擴展方法,而對於LINQ就是一個逗號分隔的列表,在orderby子句中,第一個值后面的項都屬於次要排序。

static void Main(string[] args)
{
    var students = new[]{
        new {name="Jane",age=12,gender="famale"},
        new {name="Hank",age=15,gender="male"},
        new {name="Niko",age=12,gender="male"},
        new {name="Curry",age=12,gender="male"}
    };
 
    var sorted = from n in students
                orderby n.age, n.gender
                select n;
 
    foreach (var item in sorted)
    {
        Console.WriteLine(item);
    }
 
}

轉自:http://www.cnblogs.com/heqichang/archive/2011/08/03/2126640.html

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM