Comparing things in lists?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RustyDoorknobs
    New Member
    • Jun 2010
    • 2

    #1

    Comparing things in lists?

    Hello, I'm new to csharp and was wondering about something. How can I check to see if two lists share a value? For example:

    Code:
    List<int> list1 = new List<int>();
    List<int> list2 = new List<int>();
    
    list1.Add(1);
    list1.Add(5);
    list1.Add(3);
    
    list2.Add(4);
    list2.Add(1);
    list2.Add(9);
    list2.Add(2);
    As you can see, both the lists have the number 1. How can I check this in csharp, if the lists can be any length?
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Nested loops.
    You loop through all of the indexes of List1 and compare each item to all of the indexes in List2

    Code:
    Foreach (int Yogi in List1)
    {
       Foreach (int BooBoo in List2)
       {
          if (List1[Yogi] == List2[BooBoo])
          {
             // We have a winner Ranger Smith
          }
       }
    }

    Comment

    • Curtis Rutland
      Recognized Expert Specialist
      • Apr 2008
      • 3264

      #3
      A slightly more condensed version:
      Code:
      foreach (int i in intList1)
          if (intList2.Contains(i))
              Console.WriteLine("Both lists contain: {0}", i);

      Comment

      Working...