Getting a collection of index values using a LINQ query

10,829

Solution 1

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"));

Solution 2

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);
   }
}

Solution 3

Seems fine to me. You might save a couple characters by changing the select to:

.Select((Value, Index) => new {Value, Index})

Solution 4

How about this? It's similar to the original poster's but I first select the indexes and then build a collection which matches the criteria.

var x = s.Select((a, i) => i).Where(i => s[i].StartsWith("t"));

This is a tad less efficient than some of the other answers as the list is fully iterated over twice.

Share:
10,829

Related videos on Youtube

Guy
Author by

Guy

I am a consultant specializing in TypeScript/React/JavaScript/Node.js Full Stack. I also have a strong background in C#/.Net. I am available for hire.

Updated on April 17, 2022

Comments

  • Guy
    Guy about 2 years

    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.

  • Guy
    Guy over 15 years
    Thanks - I didn't know you could do that - I thought you had to reassign.
  • Guy
    Guy over 15 years
    Thanks for the answer. I agree that this would be more efficient. As you guessed this is a simplified version of something more complex that "has" to be done in LINQ in this particular case.
  • Jon Skeet
    Jon Skeet over 15 years
    It's called a "projection initializer" - it basically takes the last subexpression (which must be a field or property) within the expression and uses that for the name. So you could do x.GetFoo().Bar and that would be equivalent to Bar=x.GetFoo().Bar.
  • Jon Skeet
    Jon Skeet over 15 years
    And that exact code only works when you're using List instead of an arbitrary IEnumerable. Otherwise you'd have to use foreach and a separate local variable.
  • Rup
    Rup almost 12 years
    "Yet the function is there, and it can be misleading." - but that would be the same for any of the other LINQ methods that use indexes, e.g. the .Select((item, index) => . I don't think it's necessarily anything wrong with Jon's function as long as you understand what you're getting.
  • MPelletier
    MPelletier almost 12 years
    @Rup I've gathered more experience with LINQ and the IEnumerable interface since that answer. I agree that if you know what you're doing, and if the function is defined, there won't be surprises. One potential hazard would be to get the indexes off an IEnumerable produced with AsParallel. Those indexes will reflect the state of how the collection was produced, but producing it again is almost guaranteed to give a different result. The indexes will refer to something that does not exist. In team work (or reusing the function later), if that behaviour isn't clear, you're gonna be in trouble.
  • Rup
    Rup almost 12 years
    I still think that the order isn't likely to change unless you modify the collection, though, and that you ought not use the indexes unless it makes sense for the structure. But I hadn't considered AsParallel - neat, thanks.