2016-03-29 111 views
0

我有一個包含許多屬性的對象列表。檢查列表<Of List<T>>是否包含列表<T>

Dim Duplicates As New List(Of ElementObject) 
Dim ListOfDuplicates As New List(Of List(Of ElementObject)) 

For Each Element As ElementObject In Duplicates 
    Dim tmpList As List(Of ElementObject) 

    'Im looking for list of elements with the same width and height in Duplicates list 
    tmpList = Duplicates.FindAll(Function(x) x.Width = Element.Width And x.Height = Element.Height) 
    tmpList = tmpLista.OrderBy(Function(x) x.Id).ToList() 

    'Here is what I want: I want to look if tmpLista is already in ListOfDuplicates, but this code does not work 
    If ListOfDuplicates.Contains(tmpList) Then 
     Continue For 
    End If 

    ListOfDuplicates.Add(tmpList) 
Next 

我該如何做到這一點,檢查我的另一個列表中的對象列表是否已經包含該列表?

+0

'tmpLista'在'tmpList = tmpLista.OrderBy(功能(X)x.Id).ToList()'似乎是一個錯字。 –

+0

不,不是,我只是改變了我的變量的命名,並忘記更改tmpList :) – XardasLord

+0

您的代碼無法工作,因爲每當您執行檢查時,tmpList都是新創建的列表。 –

回答

0

這奏效了:

Dim Contain As Boolean = ListOfDuplicates.Any(Function(x) x.SequenceEqual(tmpList)) 
1

您可以使用SequenceEqual到列表中的內容有兩點需要說明比較:

  • 名單需要進行排序相同的方式
  • 的列表中的對象必須是可以等同的。你可以通過覆蓋Equals或者通過實現一個檢查相等性的函數來做到這一點。

我更習慣於C#中的lambda表達式更容易編寫,我可以創建一個擴展類而不創建一個單獨的模塊。該類提供哈希碼計算和比較,以檢查相同值的兩個元素列表。它爲每個列表計算一組哈希代碼,對哈希代碼進行排序,然後使用SequenceEquals比較哈希代碼集。

Public Class ElementListComparer 
    Public Shared Function ListsAreEqual(list1 As IEnumerable(Of Element), list2 As IEnumerable(Of Element)) 
     If list1 Is Nothing OrElse list2 Is Nothing Then Return False 
     If Object.ReferenceEquals(list1, list2) Then Return True 
     return GetSortedHashCodes(list1).sequencequal(GetSortedHashCodes(list2)) 
    End Function 

    Public Shared Function GetSortedHashCodes(elements As IEnumerable(Of Element)) 
     Return elements.Select(Function(el As Element) As Long 
            Return CalculateHashCode(el) 
           End Function).OrderBy(Function(hashcode) 
                 Return hashcode 
                End Function) 
    End Function 

    Public Shared Function CalculateHashCode(el As Element) As Long 
     Return (el.Height * 397)^el.Width 
    End Function 
End Class 

所以,你會調用

ElementListComparer.ListsAreEqual(list1 as IEnumerable(of Element), list2 as IEnumerable(of Element)) 
相關問題