2017-06-16 102 views
0

在我的原始代碼中,我有一個包含2列的列表對象WordPercent。我對列表進行排序,但只想要回只包含Word中VB.NET將二維列表複製到一維列表中

以下列表是一些示例代碼分解成簡單的東西:

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 

任何關於我是否應該完全不同(和更好)這樣做的建議會非常感謝,因爲我試圖讓自己的頭部圍繞對象,儘管我一直都在使用它們,但我對結構和列表對象很陌生。

感謝您的任何幫助,這讓我瘋狂了一個小時。

回答

2

我覺得你很接近。嘗試:

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

+0

我試圖返回ListofWords,但我收到一個錯誤,說「類型'List(Of WordsToSort)'的值不能轉換爲'List(Of String)' - 它就好像列表中的字仍然是單維列表,我仍然可以從百分比列中獲取變量,即 msgbox(ListofWords(1).Percent) 我不確定如何使用Linq,但我不介意因爲我對SQL非常熟悉,它的非常類似於 –

+0

'List(Of String)'似乎是你的方法的正確返回類型,所以只需在上面的一個查詢之前鍵入一個'Return'。Btw。'List(Of)'總是一維的。這只是一個簡單的列表。有一個'List(Of T)',其中'T'是一個具有屬性的類,並不是一個列表多維。 – Waescher

+0

你是一個明星 - 非常感謝你 - 我會upvote你的答案,但我還沒有足夠的積分,所以個人感謝你將不得不做 - 歡呼 –