【问题标题】:Sort elements of an Array in a Linq query?在 Linq 查询中对数组的元素进行排序?
【发布时间】:2014-06-29 16:20:24
【问题描述】:

我有一个List(of Integer()),我想对整数数组的元素进行排序,所有这些都在一行中,问题是Array.Sort 方法没有返回值,这将是一个有效的方式?

例如,我的列表包含作为第一个数组元素 (MyArrayList.First) 这个数组:

{4, 5, 2, 6, 3, 1}

我需要对元素进行排序

{1, 2, 3, 4, 5, 6}

示例(不工作):

' Combos is the List(of Integer())
Combos = (From Combo As Integer() In Combos 
          Select Array.Sort(Combo)).ToList

【问题讨论】:

  • 只需使用List<>类的Sort方法:Combos.Sort();。它不会返回任何内容,因为它会对您调用它的列表进行排序。
  • @Guffa 不,如果列表元素是数组,则 List 的 Sort 方法不能也不会重新排序(至少没有在方法重载中实现比较器,但我不知道如何编写正确的比较器抱歉)。感谢您的评论
  • 对不起,我错过了使它成为数组列表的类型中的括号。

标签: .net arrays vb.net linq sorting


【解决方案1】:

这就是你要找的东西

    Combos.ForEach(Sub(x As Integer()) Array.Sort(x))

【讨论】:

    【解决方案2】:

    一行:

    Dim result = (From item As Integer() In list Select (From n As Integer In item Select n Order By n Ascending).ToArray()).ToList()
    

    【讨论】:

      【解决方案3】:

      为什么希望只使用一行?

      For Each x In combos : Array.Sort(x) : Next
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-07
        • 2016-10-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多