Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find multiple index in array

Tags:

arrays

c#

.net

linq

Say I have an array like this

  string [] fruits = {"watermelon","apple","apple","kiwi","pear","banana"};

Is there an built in function that allows me to query all the index of "apple" ? For example,

  fruits.FindAllIndex("apple"); 

will return an array of 1 and 2

If there is not, how should I implement it?

Thanks!

like image 672
Fever Avatar asked Dec 03 '13 19:12

Fever


People also ask

How to find index of an element in an array?

The index of the first element in the array that passes the test. Otherwise, -1. The findIndex () method executes the callback function once for every index in the array until it finds the one where callback returns a truthy value. If such an element is found, findIndex () immediately returns the element's index.

What does findindex return in ArrayList?

Array.prototype.findIndex () The findIndex () method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test. See also the find () method, which returns the value of an array element, instead of its index.

How does the findindex () method work?

The findIndex() method executes the function once for each element present in the array: If it finds an array element where the function returns a true value, findIndex() returns the index of that array element (and does not check the remaining values)

Why does the findindex () method not work for empty array elements?

The findIndex () method does not execute the function for empty array elements. The findIndex () method does not change the original array. Required. A function to be run for each array element.


2 Answers

LINQ version:

var indexes = fruits.Select((value, index) => new { value, index })
                    .Where(x => x.value == "apple")
                    .Select(x => x.index)
                    .ToList();

Non-LINQ version, using Array<T>.IndexOf() static method:

var indexes = new List<int>();
var lastIndex = 0;

while ((lastIndex = Array.IndexOf(fruits, "apple", lastIndex)) != -1)
{
    indexes.Add(lastIndex);
    lastIndex++;
}
like image 59
MarcinJuraszek Avatar answered Oct 07 '22 02:10

MarcinJuraszek


One way would be to write like this:

var indices = fruits
                .Select ((f, i) => new {f, i})
                .Where (x => x.f == "apple")
                .Select (x => x.i);

Or the traditional way:

var indices = new List<int>();
for (int i = 0; i < fruits.Length; i++)
    if(fruits[i] == "apple")
        indices.Add(i);
like image 45
Magnus Avatar answered Oct 07 '22 03:10

Magnus