LINQ之ThenBy,ThenByDescending

返回LINQ大全首页

ThenBy()

使用指定的比较器按升序对序列中的元素执行后续排序。

简单来说就是对使用过OrderByOrderByDescending的返回序列进行二次排序。(第一次排序优先级最高,如1,2,2,3,二次排序会对2,2排序)

注意不能直接在数组或List上使用。

MSDN

升序:

using System.Linq;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    static void Main( string[] args )
    {
        string[] fruits = { "grape", "passionfruit", "banana", "mango", "orange", "raspberry", "apple", "blueberry" };

        //以排列字符串的长度升序
        IOrderedEnumerable<string> orderByFruits    = fruits.OrderBy( value => value.Length );
        //以字母升序对长度相同的项目进行排序。
        IOrderedEnumerable<string> thenByFruits     = orderByFruits.ThenBy( value => value );

        System.Console.WriteLine("fruits  :{0}", fruits.Text());
        System.Console.WriteLine("orderBy :{0}", orderByFruits.Text());
        System.Console.WriteLine("thenBy  :{0}", thenByFruits.Text());

        System.Console.ReadKey();
    }

    public static string Text( this IEnumerable i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
} 



fruits :[grape], [passionfruit], [banana], [mango], [orange], [raspberry], [apple], [blueberry],
orderBy :[grape], [mango], [apple], [banana], [orange], [raspberry], [blueberry], [passionfruit],
thenBy :[apple], [grape], [mango], [banana], [orange], [blueberry], [raspberry], [passionfruit],

ThenByDescending()

降序:

using System.Linq;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    static void Main( string[] args )
    {
        string[] fruits = { "grape", "passionfruit", "banana", "mango", "orange", "raspberry", "apple", "blueberry" };

        //以排列字符串的长度升序
        IOrderedEnumerable<string> orderByFruits    = fruits.OrderBy( value => value.Length );
        //以字母降序对长度相同的项目进行排序。
        IOrderedEnumerable<string> thenByFruits     = orderByFruits.ThenByDescending( value => value );

        System.Console.WriteLine("fruits  :{0}", fruits.Text());
        System.Console.WriteLine("orderBy :{0}", orderByFruits.Text());
        System.Console.WriteLine("thenBy  :{0}", thenByFruits.Text());

        System.Console.ReadKey();
    }

    public static string Text( this IEnumerable i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
}



fruits :[grape], [passionfruit], [banana], [mango], [orange], [raspberry], [apple], [blueberry],
orderBy :[grape], [mango], [apple], [banana], [orange], [raspberry], [blueberry], [passionfruit],
thenBy :[mango], [grape], [apple], [orange], [banana], [raspberry], [blueberry], [passionfruit],

你也可以指定类中的某元素排序。

using System.Linq;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    private class Parameter
    {
        public int      ID      { get; set; }
        public string   Name    { get; set; }
        public int      Age     { get; set; }

        public override string ToString()
        {
            return string.Format( "ID:{0}, Age:{1}, Name:{2},", ID, Age, Name );
        }
    }

    static void Main( string[] args )
    {
        Parameter[] persons =
        {
            new Parameter() { ID = 0, Age = 30, Name = "A" },
            new Parameter() { ID = 1, Age = 25, Name = "B" },
            new Parameter() { ID = 2, Age = 18, Name = "C" },
            new Parameter() { ID = 1, Age = 30, Name = "D" },
            new Parameter() { ID = 1, Age = 25, Name = "E" },
            new Parameter() { ID = 2, Age = 15, Name = "F" },
        };

        IOrderedEnumerable<Parameter> orderByID     = persons.OrderBy( value => value.ID );
        IOrderedEnumerable<Parameter> thenByAge     = orderByID.ThenBy( value => value.Age );
        IOrderedEnumerable<Parameter> thenByName    = orderByID.ThenByDescending( value => value.Name );


        System.Console.WriteLine("persons    :{0}", persons.Text());
        System.Console.WriteLine("orderByID  :{0}", orderByID.Text());
        System.Console.WriteLine("thenByAge  :{0}", thenByAge.Text());
        System.Console.WriteLine("thenByName :{0}", thenByName.Text());

        System.Console.ReadKey();
    }

    public static string Text( this IEnumerable i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
} 


persons :[ID:0, Age:30, Name:A,], [ID:1, Age:25, Name:B,], [ID:2, Age:18, Name:C,], [ID:1, Age:30, Name:D,], [ID:1, Age:25, Name:E,], [ID:2, Age:15, Name:F,],
orderByID :[ID:0, Age:30, Name:A,], [ID:1, Age:25, Name:B,], [ID:1, Age:30, Name:D,], [ID:1, Age:25, Name:E,], [ID:2, Age:18, Name:C,], [ID:2, Age:15, Name:F,],
thenByAge :[ID:0, Age:30, Name:A,], [ID:1, Age:25, Name:B,], [ID:1, Age:25, Name:E,], [ID:1, Age:30, Name:D,], [ID:2, Age:15, Name:F,], [ID:2, Age:18, Name:C,],
thenByName :[ID:0, Age:30, Name:A,], [ID:1, Age:25, Name:E,], [ID:1, Age:30, Name:D,], [ID:1, Age:25, Name:B,], [ID:2, Age:15, Name:F,], [ID:2, Age:18, Name:C,],

但是如果直接使用为实现IComparable的类进行比较则会报错。

using System.Linq;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    private class Parameter
    {
        public int      ID      { get; set; }
        public string   Name    { get; set; }
        public int      Age     { get; set; }

        public override string ToString()
        {
            return string.Format( "ID:{0}, Age:{1}, Name:{2},", ID, Age, Name );
        }
    }

    static void Main( string[] args )
    {
        Parameter[] persons =
        {
            new Parameter() { ID = 0, Age = 30, Name = "A" },
            new Parameter() { ID = 1, Age = 25, Name = "B" },
            new Parameter() { ID = 2, Age = 18, Name = "C" },
            new Parameter() { ID = 1, Age = 30, Name = "D" },
            new Parameter() { ID = 1, Age = 25, Name = "E" },
            new Parameter() { ID = 2, Age = 15, Name = "F" },
        };

        IOrderedEnumerable<Parameter> orderByID     = persons.OrderBy( value => value.ID );
        IOrderedEnumerable<Parameter> thenByParam   = orderByID.ThenBy( value => value );
        
        try
        {
            thenByParam.Any();
        }
        catch( System.Exception i_exception )
        {
            System.Console.WriteLine( "{0}", i_exception );
            System.Console.ReadKey();
            return;
        }
        
        System.Console.WriteLine("persons     :{0}", persons.Text());
        System.Console.WriteLine("orderByID   :{0}", orderByID.Text());
        System.Console.WriteLine("thenByParam :{0}", thenByParam.Text());

        System.Console.ReadKey();
    }

    public static string Text( this IEnumerable i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
}

System.ArgumentException

通过实现IComparable,可以将其直接排序。

using System.Linq;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    private class Parameter : System.IComparable<Parameter>
    {
        public int      ID      { get; set; }
        public string   Name    { get; set; }
        public int      Age     { get; set; }

        public int CompareTo( Parameter i_other )
        {
            if( i_other == null )
            {
                return -1;
            }

            int compareID   = ID - i_other.ID;
            if( compareID != 0 )
            {
                return compareID;
            }

            int compareAge  = Age - i_other.Age;
            if( compareAge != 0 )
            {
                return compareAge;
            }
            
            return string.Compare( Name, i_other.Name );
        }

        public override string ToString()
        {
            return string.Format( "ID:{0}, Age:{1}, Name:{2},", ID, Age, Name );
        }
    }

    static void Main( string[] args )
    {
        Parameter[] persons =
        {
            new Parameter() { ID = 0, Age = 30, Name = "A" },
            new Parameter() { ID = 1, Age = 25, Name = "B" },
            new Parameter() { ID = 2, Age = 18, Name = "C" },
            new Parameter() { ID = 1, Age = 30, Name = "D" },
            new Parameter() { ID = 1, Age = 25, Name = "E" },
            new Parameter() { ID = 2, Age = 15, Name = "F" },
        };

        IOrderedEnumerable<Parameter> orderByID     = persons.OrderBy( value => value.ID );
        IOrderedEnumerable<Parameter> thenByParam   = orderByID.ThenBy( value => value );

        System.Console.WriteLine("persons     :{0}", persons.Text());
        System.Console.WriteLine("orderByID   :{0}", orderByID.Text());
        System.Console.WriteLine("thenByParam :{0}", thenByParam.Text());

        System.Console.ReadKey();
    }

    public static string Text( this IEnumerable i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
}

persons :[ID:0, Age:30, Name:A,], [ID:1, Age:25, Name:B,], [ID:2, Age:18, Name:C,], [ID:1, Age:30, Name:D,], [ID:1, Age:25, Name:E,], [ID:2, Age:15, Name:F,],
orderByID :[ID:0, Age:30, Name:A,], [ID:1, Age:25, Name:B,], [ID:1, Age:30, Name:D,], [ID:1, Age:25, Name:E,], [ID:2, Age:18, Name:C,], [ID:2, Age:15, Name:F,],
thenByParam :[ID:0, Age:30, Name:A,], [ID:1, Age:25, Name:B,], [ID:1, Age:25, Name:E,], [ID:1, Age:30, Name:D,], [ID:2, Age:15, Name:F,], [ID:2, Age:18, Name:C,],

即使是string、int等也可以通过IComparer自定义比较规则。

using System.Linq;
using System.Collections;
using System.Collections.Generic;

public static class Program
{
    private class CompareString : IComparer<string>
    {
        public int Compare( string i_lhs, string i_rhs )
        {
            bool isInitiallyG_L = !string.IsNullOrEmpty( i_lhs ) ? i_lhs.StartsWith( "g" ) : false;
            bool isInitiallyG_R = !string.IsNullOrEmpty( i_rhs ) ? i_rhs.StartsWith( "g" ) : false;

            if( isInitiallyG_L && !isInitiallyG_R )
            {
                return -1;
            }
            if( !isInitiallyG_L && isInitiallyG_R )
            {
                return 1;
            }
            
            return string.Compare( i_lhs, i_rhs );
        }
    }
    static void Main( string[] args )
    {
        string[] fruits = { "grape", "passionfruit", "banana", "mango", "orange", "raspberry", "apple", "blueberry" };

        IOrderedEnumerable<string> orderByFruits    = fruits.OrderBy( value => value.Length );
        
        CompareString compare = new CompareString();
        IOrderedEnumerable<string> thenByFruits     = orderByFruits.ThenBy( value => value, compare);

        System.Console.WriteLine("fruits  :{0}", fruits.Text());
        System.Console.WriteLine("orderBy :{0}", orderByFruits.Text());
        System.Console.WriteLine("thenBy  :{0}", thenByFruits.Text());

        System.Console.ReadKey();
    }

    public static string Text( this IEnumerable i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
}

fruits :[grape], [passionfruit], [banana], [mango], [orange], [raspberry], [apple], [blueberry],
orderBy :[grape], [mango], [apple], [banana], [orange], [raspberry], [blueberry], [passionfruit],
thenBy :[grape], [apple], [mango], [banana], [orange], [blueberry], [raspberry], [passionfruit],
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我寄人间雪满头丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值