2012-05-25 103 views
1

我有一個List<A>,其中A包含了一個名爲TypeId財產和List<B>,其中B還含有一種叫物業TypeId如何在ListA中選擇具有與ListB中的項目屬性相匹配的屬性的項目?

我想從List<A>選擇所有項目,其中List<B>包含項目,其中B.TypeId == A.TypeId

ListA.Add(new A { TypeId = 1 }); 
ListA.Add(new A { TypeId = 2 }); 
ListA.Add(new A { TypeId = 3 }); 

ListB.Add(new B { TypeId = 3 }); 
ListB.Add(new B { TypeId = 4 }); 
ListB.Add(new B { TypeId = 1 }); 

???? // Should return items 1 and 3 only 

這樣做的最有效方法是什麼?

我知道它的簡單的東西,但我的大腦感覺今天愚蠢....

回答

4

使用LINQ,它使用join方法是相當簡單的。

var join = ListA.Join(ListB, la => la.TypeId, lb => lb.TypeId, (la, lb) => la); 
0

我想你正在嘗試做一個相交操作,它應該可能與Intersect擴展。這裏的一個優點是相交將在O(m + n)中運行。 示例程序:

class Program 
{ 
    class Bar 
    { 
     public Bar(int x) 
     { 
      Foo = x; 
     } 
     public int Foo { get; set; } 
    } 

    class BarComparer : IEqualityComparer<Bar> 
    { 
     public bool Equals(Bar x, Bar y) 
     { 
      return x.Foo == y.Foo; 
     } 

     public int GetHashCode(Bar obj) 
     { 
      return obj.Foo; 
     } 

    } 
    static void Main(string[] args) 
    { 
     var list1 = new List<Bar>() { new Bar(10), new Bar(20), new Bar(30)}; 
     var list2 = new List<Bar>() { new Bar(10), new Bar(20) }; 
     var result = list1.Intersect(list2, new BarComparer()); 

     foreach (var item in result) 
     { 
      Console.WriteLine(item.Foo); 
     } 
    } 
} 
相關問題