Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the list of index for a string in an array? [duplicate]

Tags:

c#

I have one array:

string[] cars = {"Volvo", "BMW", "Volvo", "Mazda","BMW","BMW"};

I m looking for the index of BMW, and I using below code to get:

Label1.Text = Array.FindIndex(filterlistinput, x => x.Contains("BMW")).ToString();

Unfortunately it return the result for the first BMW index only. Current output:

 1

My expected output will be

{1,4,5}
like image 388
Shi Jie Tio Avatar asked Jan 03 '20 08:01

Shi Jie Tio


People also ask

How do you find the index of duplicate elements in an array?

indexOf() function. The idea is to compare the index of all items in an array with an index of their first occurrence. If both indices don't match for any item in the array, you can say that the current item is duplicated. To return a new array with duplicates, use the filter() method.

How do you go through a list and search if there is a duplicate element in Java?

One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.


1 Answers

You can do something as follows

string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
// Get indices of BMW 
var indicesArray = cars.Select((car, index) => car == "BMW" ? index : -1).Where(i => i != -1).ToArray();
// Display indices
Label1.Text = string.Join(", ", indicesArray);
like image 147
Shahid Manzoor Bhat Avatar answered Nov 15 '22 08:11

Shahid Manzoor Bhat