edamamevv
edamamevv

Reputation: 13

C# List of Integer Arrays does not Contain Item

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.

Upvotes: 1

Views: 522

Answers (3)

lidqy
lidqy

Reputation: 2453

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)> {
                (1, 3),
                (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);

Upvotes: 1

Charlieface
Charlieface

Reputation: 71579

From OP

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,

Upvotes: 0

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

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.

Upvotes: 3

Related Questions