2014-09-03 61 views
-4

我有一個通用的List(Of T)與一堆項目包含一些重複值在.ItemID。我需要代碼才能返回重複項,但下面的代碼會返回所有項目。查找重複列表(T)使用LINQ VB .NET不工作

Dim items As List(Of ItemsClass.ItemCollection) = _ 
     New List(Of ItemsClass.ItemCollection)(oleObj.ListOfItemsToCopy(listViewItems)) 'Returns a list of items 

Dim duplicates = From c In items Where (c.ItemID.Count > 1) Select c 'Needs to return duplicate items 

List(Of ItemCollection)項目的一個例子是如下

項ID,製作,式樣年

123456福特獵鷹1999年

123457馬自達CX6 2001

123456 Ford Ranger 2002

我需要組ItemID並返回所有重複的結果

+0

你需要返回所有的重複項目或只是其中一個重複項目? (因爲每個具有相同ID的項目將具有相同的值,對吧?) – Enigmativity 2014-09-03 02:47:16

+0

@Enigmativity我需要返回所有重複的ItemID,因爲它們包含不同的值。 – 2014-09-03 03:16:22

+0

那麼這是否指出了「ItemID」值被重用的一個潛在問題? – Enigmativity 2014-09-03 04:52:42

回答

4

對於那些有興趣,下面的工作很適合我

Public Class Form1 
Private Class ItemsCollection 
    Private _name As String 
    Public Property name() As String 
     Get 
      Return _name 
     End Get 
     Set(value As String) 
      _name = value 
     End Set 
    End Property 
    Private _data As String 
    Public Property data() As String 
     Get 
      Return _data 
     End Get 
     Set(value As String) 
      _data = value 
     End Set 
    End Property 
End Class 
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 

    Dim items As List(Of ItemsCollection) = New List(Of ItemsCollection)() 

    items.Add(New ItemsCollection With {.name = "Test", .data = "Test2"}) 
    items.Add(New ItemsCollection With {.name = "Test1", .data = "Test2"}) 
    items.Add(New ItemsCollection With {.name = "Test3", .data = "Test4"}) 

    For Each item As ItemsCollection In items.GroupBy(Function(x) x.data).Where(Function(x) x.Count > 1).SelectMany(Function(x) x) 
     ListBox1.Items.Add(item.name + " " + item.data) 
    Next 

End Sub 
End Class 

輸出

Test Test2 
Test1 Test2 
0

這裏已經來到C#語法這一點,顯示操作用於檢測LINQ重複的一般方法,但它需要被轉換以VB.NET語法爲依據。

該代碼也需要自由定義T爲「類型,其具有的ItemID性的單個項」;我不確定爲什麼/如何ItemCollection類型的用武之地。

IEnumerable<T> items = ..; 

// Group the items 
var groupsById = items.GroupBy(i => i.ItemID); 

// Find the groups with more than one item 
// (The items in the resulting groups are duplicates of each other) 
var groupsWithDups = groupsById.Where(g => g.Length > 1); 

// If the source is [1, 2, 4, 1, 2, 2] the output will 
// contain the following [1, 1, 2, 2, 2]. 
IEnumerable<T> allDups = groupsWithDups.SelectMany(g => g); 
+0

如果您不知道答案,請不要評論。我需要適合VB的語法。我知道如何在C#中做到這一點,但我需要知道在VB中,特別是語法。是的,我看到了我通過不分組而犯的錯誤。 – 2014-09-03 02:19:04

+4

VB語法不應該有很大的不同。這很可能是一種直接轉碼。 – 2014-09-03 02:19:38

+0

'List duplicateItemsList = new List (x => x.Count()> 1)。選擇(x => x.Key).ToList());'這是我將如何在C#中執行它 – 2014-09-03 02:19:57