【问题标题】:VB.NET copy a 2-dimenion List into a one dimension listVB.NET 将二维列表复制到一维列表中
【发布时间】:2017-11-18 21:12:44
【问题描述】:

在我的原始代码中,我有一个包含 2 列的列表对象,WordPercent。我对列表进行了排序,但只想返回仅包含单词的列表

下面是一些简单的示例代码:

Public Function SortMyWords() as list(of string)
    Dim Words As WordsToSort
    Dim ListofWords As New List(Of WordsToSort)

    Words.Word = "John"
    Words.Percent = "10"
    ListofWords.Add(Words)

    Words.Word = "Robert"
    Words.Percent = "1"
    ListofWords.Add(Words)

    ListofWords = ListofWords.OrderBy(Function(x) x.Percent).ToList()
End Sub

Public Structure WordsToSort
    Public Word As String
    Public Percent As String

    Public Sub New(ByVal _word As String, ByVal _percent As String)
        Word = _word
        Percent = _percent
    End Sub
End Structure

SortMyWords 函数的末尾,我想将Word 列作为列表返回,我不确定我是否可以直接执行此操作 - 即 Return Listofwords(column Word) 或者我是否需要将我的 ListofWords 复制到一个新列表中,只包含列字 - 类似这样的东西(不起作用)

Dim Newlist As New List(Of String)
Newlist.AddRange(ListofWords(Words.Word))
Return NewList

任何关于我是否应该以完全不同的方式(更好)来做这件事的建议都会非常感激,因为我正试图让我的头脑围绕对象,虽然我一直在使用它们,但我对结构和列表对象还是陌生的。

感谢您的帮助,这已经让我发疯了一个小时。

【问题讨论】:

    标签: vb.net list


    【解决方案1】:

    我认为你很接近。试试:

    ListOfWords
        .OrderBy(Function(x) x.Percent)
        .Select(Function(x) x.Word)
        .ToList()
    

    如果您愿意,也可以使用 LINQ 语法:

    (from w in ListOfWords
        orderby w.Percent ascending
        select w.Word).ToList()
    

    请注意,返回类型是 List(Of String) 而不是 List(Of WordsToSort)。因此,您不能像在示例代码中那样再次将其分配回变量 ListOfWords

    【讨论】:

    • 我试图返回 ListofWords 但我收到一条错误消息,提示“'List(Of WordsToSort)' 类型的值不能转换为 'List(Of String)' - 就好像它仍然是 listofwords一维列表,我仍然可以从百分比列中获取变量,即 msgbox(ListofWords(1).Percent) 我不确定如何使用 Linq,但我不介意知道,因为我很熟悉SQL 和它非常像 sql
    • List(Of String) 似乎是您方法的正确返回类型。因此,只需在上述查询之一之前输入Return。顺便提一句。 List(Of ) 始终是一维的。这只是一个简单的列表。有一个 List(Of T) 其中T 是一个具有属性的类不会使列表成为多维的。
    • 你是明星 - 真的非常感谢 - 我会赞成你的回答,但我还没有足够的分数,所以你必须做个人感谢 - 干杯
    • 分数不足以将答案标记为解决方案?不知道这是一回事……
    • @Waescher 他们can't upvote 因为他们缺少the privilege,但他们可以接受。他们可能没有接受the tour
    猜你喜欢
    • 1970-01-01
    • 2021-08-06
    • 2011-06-25
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 2023-02-19
    • 2022-12-29
    • 1970-01-01
    相关资源
    最近更新 更多