Home > front end >  C# List of Integer Arrays does not Contain Item
C# List of Integer Arrays does not Contain Item

Time:11-18

My goal is to add an unknown number of integer coordinates to a collection. While I can add these coordinates to this list List<int[]> coordList = new List<int[]>(); I cannot check if coordList.Contains(specifiedCoordinate).

This is what I have so far:

List<int[]> coordList = new List<int[]>();
coordList.Add(new int[] {1, 3});
coordList.Add(new int[] {3, 6});
bool contains = coordList.Contains(new int[]{1, 3})
Console.WriteLine(contains);

However, contains is always false even though I specify the same values that I add. I have tried ArrayList as a possible alternative, but the results are the same as using List.

If there's something I'm not understanding or if there's an alternative, I'm all ears.

Thank you!

Answer

So, I created a new function based on Llama's suggestion:

static bool ContainsCoordinate(int[] coords, List<int[]> coordList) {
    bool contains = coordList.Any(a => a.SequenceEqual(coords));
    return contains;
}

Which just works a charm.

I would also like to thank Ron Beyer for helping me understand more about object declaration and instancing,

Cheers fellas!

CodePudding user response:

It seems like you want:

bool contains = coordList.Any(a => a.SequenceEqual(new int[]{1, 3}));

SequenceEqual docs.

.Any and .SequenceEqual are extension methods provided by the System.Linq namespace. You may need to ensure that you have using System.Linq; at the top of your code file to make this work.

CodePudding user response:

If you'd use value tuples, you'd get the value-comparison for free, also the code gets neater:

        var coordList = new List<(int x, int y)>();
        coordList.Add((1, 3));
        coordList.Add((3, 6));
        //contains is now true because 
        //value tuples do value comparison in their 'Equals' override 
        bool contains = coordList.Contains((1, 3));
        Console.WriteLine(contains);
  • Related