2012-07-31 10 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(); 
     } 
संबंधित मुद्दे