0

trying to print "Success" in the console in the following code:

static void Main(string[] args)
{
    List<int[]> listInt = new List<int[]>();

    listInt.Add(new int[] { 1, 2 });
    listInt.Add(new int[] { 3, 4 });
    listInt.Add(new int[] { 5, 6 });
    listInt.Add(new int[] { 7, 8 });
    listInt.Add(new int[] { 9, 10 });
    listInt.Add(new int[] { 11, 12 });
    listInt.Add(new int[] { 12, 13 });
    listInt.Add(new int[] { 13, 14 });

    int[] testing = new int[] { 7, 8 };

    if(listInt.Contains(testing))
    {
        Console.WriteLine("Success");
    }
    else 
    {
        Console.WriteLine("Failure");
    }
}

However it keeps printing "Failure". Does anyone have any simple solutions where I can test to see if a List<int[]> contains the int[] testing?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Sean
  • 57
  • 6
  • 2
    The default `Equals` comparison of arrays considers two array equal if they are the exact same reference, not if they have the same content. You might use `listInt.Any(a => a.SequenceEqual(testing))` to get contant comparison. – Klaus Gütter May 15 '23 at 04:17
  • The first solution appears to work, thank you! The SO questions' solution doesn't work as I'm comparing between a List and an int[], not 2 arrays. – Sean May 15 '23 at 04:22
  • Of course you're comparing two arrays. Each item in the `List` is an array and you're comparing each one to another array. The fact that you're comparing two arrays multiple times doesn't change the fact that you're comparing two arrays. – jmcilhinney May 15 '23 at 04:30
  • I am new to OOP, apologies. The suggested solution on SO threw an error though, something about array length not being equal – Sean May 15 '23 at 04:37
  • @KlausGütter Can you post your comment as an answer? It worked perfectly. – Sean May 31 '23 at 06:45

1 Answers1

0

You can use linq to

List<int[]> listInt = new List<int[]>();

            listInt.Add(new int[] { 1, 2 });
            listInt.Add(new int[] { 3, 4 });
            listInt.Add(new int[] { 5, 6 });
            listInt.Add(new int[] { 7, 8 });
            listInt.Add(new int[] { 9, 10 });
            listInt.Add(new int[] { 11, 12 });
            listInt.Add(new int[] { 12, 13 });
            listInt.Add(new int[] { 13, 14 });

      int[] testing =
          new int[] { 7,8};

int index =listInt.FindIndex(l =>
    Enumerable.SequenceEqual(testing, l));

    
            if(index>0)
            {
                Console.WriteLine("Success");
            }
            else 
            {
                Console.WriteLine("Failure");
            }

abolfazl sadeghi
  • 2,277
  • 2
  • 12
  • 20