简体   繁体   English

list.sort,但groupby结束数字

[英]list.sort, but groupby ending numbers

I have a list of items I would like to group by the last two ending numbers, so: 我有一个项目列表,我想按最后两个结束数字分组,所以:

127658
012345
123456
123457
123458
012345

would sort as: 将排序为:

012345
012345
123456
123457
123458
127658

How is this accomplished by overloading list.sort? 如何通过重载list.sort来实现这一点? The output would be very similar to say, an excel autofilter, "ENDS WITH 00" 输出将非常类似于excel自动过滤器,“ENDS WITH 00”

No overload is needed. 不需要过载。 Just use a lambda: 只需使用lambda:

list.OrderBy(Function(n) Cint(n.toString().Substring(n.toString().Length-2))).
     ThenBy(Function(n) n)

This is a really polished solution. 这是一个非常优秀的解决方案。


As Steven Doggart pointed out, you can check for numbers shorter than 2 digits: 正如Steven Doggart指出的那样,您可以检查短于2位的数字:

list.OrderBy(Function(n) Cint(n.toString().
             Substring(n.toString().Length - Math.Min(n.ToString().Length, 2)))).
     ThenBy(Function(n) n)

Or, even simple, using part of MarcinJuraszek 's answer: 或者,甚至简单,使用MarcinJuraszek的部分回答:

list.OrderBy(Function(n) n Mod 100).ThenBy(Function(n) n)

It looks quite easy. 看起来很容易。 Compare function: 比较功能:

Public Shared Function CompareByLastTwo(x As Integer, y As Integer) As Integer
    Return (x Mod 100).CompareTo(y Mod 100)
End Function

And usage: 用法:

Dim items as List(Of Integer)

(...)

items.Sort(CompareByLastTwo)

I assumed your items are Integer 我假设你的物品是Integer

This should work (presuming a List(Of String) ): 这应该工作(假设一个List(Of String) ):

list = list.Select(Function(num) New With {
               .Num = num,
               .LastTwo = If(num.Length < 2, num, num.Substring(num.Length - 2))
           }).
        OrderBy(Function(x) x.LastTwo).
        ThenBy(Function(x) x.Num).
        Select(Function(x) x.Num).ToList()

If it's a List(Of Int32) the same approach: 如果它是List(Of Int32)的方法相同:

intList = intList.
    Select(Function(num) New With {.Num = num, .Str = num.ToString()}).
    Select(Function(x) New With {
        x.Num,
        x.Str,
        .LastTwo = If(x.Str.Length < 2, x.Str, x.Str.Substring(x.Str.Length - 2))
    }).
    OrderBy(Function(x) x.LastTwo).
    ThenBy(Function(x) x.Num).
    Select(Function(x) x.Num).ToList()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM