2011-05-11 50 views
1

我有2個字典;從字典(int64,int64)中過濾字典(int64,myObject)

  • 答:字典(int64類型的,myObject的)
  • B:字典(int64類型的,int64類型)。

我想過濾(或得到另一個過濾的字典)字典A字典B.我的意思是,dictonary B包含字典A鍵的一些鍵/值,我只想要一個字典只有這些鍵。爲了以防萬一,B不是(int64,int64)的字典,它可以是列表,數組或任何其他的東西,如果它有幫助的話。

非常感謝! PS:我知道我可以在裏面做一個for,但我想(希望?)會有更有效的方式來做到這一點。

回答

1

這有幫助嗎? Customerint64類型的一個屬性ID

Dim foo As New Dictionary(Of Int64, Int64) 
    Dim bar As New Dictionary(Of Int64, Customer) 

    foo.Add(1, 5) 
    foo.Add(2, 99) 
    foo.Add(3, 222) 
    foo.Add(4, 333) 

    bar.Add(1, New Customer(5, "john")) 
    bar.Add(55, New Customer(323, "ringo")) 
    bar.Add(4, New Customer(333, "george")) 

    Dim common = From f In foo, b In bar _ 
        Where f.Key = b.Key _ 
        And f.Value = b.Value.ID _ 
        Select b 

    For Each item As KeyValuePair(Of Int64, Customer) In common 
     Console.WriteLine(item.Key & " " & item.Value.ID & " " & item.Value.Name) 
    Next 

.... 

Public Class Customer 
    Public ID As Int64 
    Public Name As String 
End Class 
+0

嗨!它的工作,非常感謝你!然而,我不知道如何將「普通」轉換爲字典(int64,myobject)。我試過在common.todictionary中使用KeySelector As Func(Of MyObject,Int64),但是我得到一個錯誤。我會感謝您的建議!謝謝! – Leo 2011-05-11 22:52:48

+0

@Leo - 看看修改後的答案。 – 2011-05-11 23:01:05

+0

非常感謝。問題是我無法將「common」轉換爲字典(int64,myobject)。無論如何,我已經改變了被調用函數中的一個參數來接受「通用」類型。問候! – Leo 2011-05-26 17:24:22