Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search for the index of an int[2] in a list?

So, I'm poking around at being able to search for the index of an int[2] in a list but I haven't had much luck.

Below is the code I've been playing with:

var coordinates = new List<int[]>();
coordinates.Add(new int[] { 1, 2 });
coordinates.Add(new int[] { 3, 4 });
coordinates.Add(new int[] { 5, 6 });

//foreach (int[] array in coordinates)
//{
//    Console.WriteLine(string.Join(", ", array));
//}

coordinates.AddRange(new int[3][] { [7, 8], [9, 10], [11, 12] });
foreach (int[] array in coordinates)
{
    Console.WriteLine(string.Join(", ", array));
}

//var index = coordinates.IndexOf([3,4]);
var index = coordinates.IndexOf(new int[] { 3, 4 });
Console.WriteLine(index);

Both the above IndexOf lines have returned a value of -1 so I assume my syntax is wrong (or I'm using the wrong tools, which is also possible). Any suggestions?

like image 426
J B Avatar asked Oct 26 '25 13:10

J B


2 Answers

Arrays in C# are reference types. They are equal to each other when the underlying object is the same.

In your code, you use new keyword when searching for matching array, which creates new underlying array object, just with the same elements, but it is different object underneath.

To correctly find index of an array with desired items you can first find the desired array (by using FirstOrDefault and SequenceEqual - mind that items must be in order for that to work) and then look for its index, like below:

var matchingArray = coordinates.FirstOrDefault(x => x.SequenceEqual(new int[] { 3, 4 }));
var index = coordinates.IndexOf(matchingArray);

If you use C# 12, you can use collection expression:

x.SequenceEqual([3, 4])
like image 89
Michał Turczyn Avatar answered Oct 29 '25 02:10

Michał Turczyn


IndexOf method will not work directly on array elements since it uses the Equals method for arrays. This checks for reference equality rather than content equality. Therefore, you need to compare the contents of the arrays manually.

So, instead of using int array I would prefer values represented as strings which makes easy to find the index of the value.

using System.Collections.Generic;

var coordinates = new List<string>();
coordinates.Add("1,2");
coordinates.Add("3,4");
coordinates.Add("5,6");
coordinates.Add("7,8");
coordinates.Add("9,10");
coordinates.Add("11,12");

foreach (string item in coordinates)
{
    Console.WriteLine(item);
}

var _valueToSearch = "7,8";
var index = coordinates.IndexOf(_valueToSearch);
Console.WriteLine(index);

Also, you may try to implement your own search logic some thing like this:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var coordinates = new List<int[]>();
        coordinates.Add(new int[] { 1, 2 });
        coordinates.Add(new int[] { 3, 4 });
        coordinates.Add(new int[] { 5, 6 });
        coordinates.AddRange(new int[3][] { new int[] { 7, 8 }, new int[] { 9, 10 }, new int[] { 11, 12 } });

        foreach (int[] array in coordinates)
        {
            Console.WriteLine(string.Join(", ", array));
        }

        var _valueToSearch = new int[] { 3, 4 };

        int index = FindIndex(coordinates, _valueToSearch);
        Console.WriteLine(index);
    }

    static int FindIndex(List<int[]> list, int[] valueToSearch)
    {
        for (int i = 0; i < list.Count; i++)
        {
            if (AreArraysEqual(list[i], valueToSearch))
            {
                return i;
            }
        }
        return -1; // Not found
    }

    static bool AreArraysEqual(int[] array1, int[] array2)
    {
        if (array1.Length != array2.Length)
        {
            return false;
        }

        for (int i = 0; i < array1.Length; i++)
        {
            if (array1[i] != array2[i])
            {
                return false;
            }
        }

        return true;
    }
}
like image 29
Ozan BAYRAM Avatar answered Oct 29 '25 03:10

Ozan BAYRAM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!