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}
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With