Assuming I have the following string array:
string[] str = new string[] {"max", "min", "avg", "max", "avg", "min"}
Is it possbile to use LINQ to get a list of indexes that match one string?
As an example, I would like to search for the string "avg" and get a list containing
2, 4
meaning that "avg" can be found at str[2] and str[4].
Simply do : int index = List. FindIndex(your condition);
.Select
has a seldom-used overload that produces an index. You can use it like this:
str.Select((s, i) => new {i, s}) .Where(t => t.s == "avg") .Select(t => t.i) .ToList()
The result will be a list containing 2 and 4.
Documentation here
You can do it like this:
str.Select((v,i) => new {Index = i, Value = v}) // Pair up values and indexes .Where(p => p.Value == "avg") // Do the filtering .Select(p => p.Index); // Keep the index and drop the value
The key step is using the overload of Select
that supplies the current index to your functor.
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