2012-07-31 40 views
10
List<int> one //1, 3, 4, 6, 7 
List<int> second //1, 2, 4, 5 

如何從一個列表中獲取所有元素並且還出現在第二個列表中?比較兩個列表以搜索常見項目

在這種情況下應該是:1,4

我談當然大約方法沒有的foreach。相反LINQ查詢

回答

38

您可以使用Intersect方法。

var result = one.Intersect(second); 

實施例:

void Main() 
{ 
    List<int> one = new List<int>() {1, 3, 4, 6, 7}; 
    List<int> second = new List<int>() {1, 2, 4, 5}; 

    foreach(int r in one.Intersect(second)) 
     Console.WriteLine(r); 
} 

輸出:

1
static void Main(string[] args) 
     { 
      List<int> one = new List<int>() { 1, 3, 4, 6, 7 }; 
      List<int> second = new List<int>() { 1, 2, 4, 5 }; 

      var result = one.Intersect(second); 

      if (result.Count() > 0) 
       result.ToList().ForEach(t => Console.WriteLine(t)); 
      else 
       Console.WriteLine("No elements is common!"); 

      Console.ReadLine(); 
     }