【问题标题】:Sort List(Of T1) by another List(Of T2)按另一个列表(T2)排序列表(T1)
【发布时间】:2021-03-10 07:56:47
【问题描述】:

有 2 个列表。第一个是List(Of Integer),第二个是List(Of String)。第一个按大小升序排列。第二个列表将以相同的方式重新排序。 这适用于我的解决方案。

有人可以向我解释this 线程中的人做了什么吗?我在这里找到了很多关于它的线程,但我不明白一些解决方案。所以我想问一下,你能不能给我解释一下。提前致谢。

我的解决方案:我的想法是将排序的整数列表写入第二个整数列表,将字符串列表写入第二个字符串列表。起初,我以为我可以使用IEnumerable

Public NotInheritable Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim IList As New List(Of Integer) From {4, 2, 3, 1, 5}
        Dim NList As New List(Of String) From {"Zacharias", "Cäsar", "Bernd", "Aaron", "Dieter"}
        Dim query As IEnumerable(Of Integer) = IList.OrderBy(Function(x) x)

        Dim IList_s As New List(Of Integer)
        For Each item In query
            IList_s.Add(item)
        Next

        Dim NList_s As New List(Of String)

        For a As Integer = 0 To NList.Count - 1 Step 1 'the new list must offer as many places as the old list.
            NList_s.Add("")
        Next
        For i As Integer = 0 To NList.Count - 1 Step 1
            For j As Integer = 0 To NList.Count - 1 Step 1
                If IList(i) = IList_s(j) Then
                    NList_s(j) = NList(i)
                End If
            Next
        Next
    End Sub
End Class

【问题讨论】:

  • 两个列表中的任何一个元素都应该是唯一的吗?
  • 解必须是 {1, 2, 3, 4, 5} 和 {"Aaron", "Caesar", "Bernd", "Zacharias", "Dieter"}。所以是的,unqiue。
  • NList = NList.Select(Function(x, i) NList(IList(i) - 1)).ToList()。之后订购IList。将IList 的名称更改为其他名称,即already taken
  • 感谢 Jimi,也感谢您指出 IList 也是一个常用词。 :)

标签: vb.net


【解决方案1】:

您可以将Zip 两个列表合并成一个新类型,然后按数字部分排序:

Dim List1 As New List(Of Integer) From {4, 2, 3, 1, 5}
Dim List2 As New List(Of String) From {"Zacharias", "Cäsar", "Bernd", "Aaron", "Dieter"}
Dim Zipped = List1.Zip(List2, Function(Number, Name) New With {Key Number, Key Name}).OrderBy(Function(pair) pair.Number)
For Each pair In Zipped
    Debug.Print(pair.Number & ", " & pair.Name)
Next

输出:

1, Aaron
2, Cäsar
3, Bernd
4, Zacharias
5, Dieter

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 2020-06-29
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多