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

2番目のリストにもあるリストからすべての要素を取得するにはどうすればよいですか?この場合2つのリストを比較して共通のアイテムを検索する

する必要があります:1、私はforeachのなしの方法については、もちろん話4

。むしろ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(); 
     } 
関連する問題