zoukankan      html  css  js  c++  java
  • Linq学习总结(6)——排序

    通过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);
        }
    
    }
  • 相关阅读:
    C# Enum设计和使用的相关技巧
    Bat文件编写
    js cookie操作
    Android use custom html tag in TextView
    Charset , Encoding
    Android View (transship)
    Android About ContentProvider
    android,create text file in sdcard
    Eclipse Shortcuts
    Common Terminology
  • 原文地址:https://www.cnblogs.com/heqichang/p/2126640.html
Copyright © 2011-2022 走看看