I discussed this interesting problem with a colleague and at first I thought JonSkeet's solution was great, but my colleague pointed out one problem, namely that if the function is an extension to IEnumerable<T>
, then it can be used where a collection implements it.
With an array, it's safe to say the order produced with foreach
will be respected (i.e. foreach
will iterate from first to last), but it would not necessarily be the case with other collections (List, Dictionary, etc), where foreach
would not reflect necessarily "order of entry". Yet the function is there, and it can be misleading.
In the end, I ended up with something similar to tvanfosson's answer, but as an extension method, for arrays:
public static int[] GetIndexes<T>(this T[]source, Func<T, bool> predicate)
{
List<int> matchingIndexes = new List<int>();
for (int i = 0; i < source.Length; ++i)
{
if (predicate(source[i]))
{
matchingIndexes.Add(i);
}
}
return matchingIndexes.ToArray();
}
Here's hoping List.ToArray
will respect the order for the last operation...