Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a collection of index values using a LINQ query

Is there a better way to do this?

string[] s = {"zero", "one", "two", "three", "four", "five"};

var x = 
s
.Select((a,i) => new {Value = a, Index = i})
.Where(b => b.Value.StartsWith("t"))
.Select(c => c.Index);

i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.

like image 500
Guy Avatar asked Oct 26 '08 02:10

Guy


2 Answers

You could easily add your own extension method:

public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    int index=0;
    foreach (T element in source)
    {
        if (predicate(element))
        {
            yield return index;
        }
        index++;
    }
}

Then use it with:

string[] s = {"zero", "one", "two", "three", "four", "five"};
var x = s.IndexesWhere(t => t.StartsWith("t"));
like image 113
Jon Skeet Avatar answered Oct 22 '22 17:10

Jon Skeet


If you're just using the example as a way to learn LINQ, ignore this post.


It's not clear to me that LINQ is actually the best way to do this. The code below seems like it would be more efficient since no new anonymous type needs to be created. Granted, your example may be contrived and the technique might be more useful in a different context, for example in a data structure where it could take advantage of an index on value, but the code below is reasonably straight-forward, understandable (no thought required) and arguably more efficient.

string[] s = {"zero", "one", "two", "three", "four", "five"};
List<int> matchingIndices = new List<int>();

for (int i = 0; i < s.Length; ++i) 
{
   if (s[i].StartWith("t"))
   {
      matchingIndices.Add(i);
   }
}
like image 21
tvanfosson Avatar answered Oct 22 '22 17:10

tvanfosson