Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of an array in List of arrays in C#

Tags:

arrays

c#

list

If you had a List of arrays like:

List<int[]> ListOfArrays = new List<int[]>();
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 2, 1 });

How would you find the index of { 2, 1} in the List?

I do not want to use an iteration loop. I would like a concise method like the one suggested by PaRiMaL RaJ in Check if string array exists in list of string:

list.Select(ar2 => arr.All(ar2.Contains)).FirstOrDefault();

(the above code will return true if members of a given string array exist in a list of string arrays)

like image 621
Saeid Avatar asked Oct 31 '15 12:10

Saeid


People also ask

How do you find the index of an array of arrays?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How do you get the index of an element in a list in C?

To find the index of specified element in given Array in C programming, iterate over the elements of array, and during each iteration check if this element is equal to the element we are searching for.

Can you index arrays in C?

Arrays in C are indexed starting at 0, as opposed to starting at 1. The first element of the array above is point[0]. The index to the last value in the array is the array size minus one.

How can I see all array indexes at once?

We can use the keyword 'declare' with a '-p' option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME.


2 Answers

var myArr = new int[] { 2, 1 };
List<int[]> ListOfArrays = new List<int[]>();
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 4, 1 });
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 2, 1 });

int index = ListOfArrays.FindIndex(l => Enumerable.SequenceEqual(myArr, l));
like image 190
Evgeni Dimitrov Avatar answered Sep 22 '22 08:09

Evgeni Dimitrov


You can use the SequenceEqual method for this. See MSDN: https://msdn.microsoft.com/en-us/library/vstudio/bb348567(v=vs.100).aspx

like image 41
Markus Gilli Avatar answered Sep 24 '22 08:09

Markus Gilli