1

Something similar to linq find in which position is my object in List, except his accepted answer is evaluating at an object level.

Say I have

public interface IFoo{
    string text {get;set;}
    int number {get;set;}
}

and

public class Foo : IFoo{
    public string text {get;set;}
    public int number {get;set;}
}

Now I have a list collection of IFoo like so:

public IList<IFoo> Foos;

I want to write a method that brings back the index(es) of Foos based upon a property value and/ or values (for example, text or number in this case) so I can do something like:

var fooIndexes = Foos.GetIndexes( f => f.text == "foo" && f.number == 8 );

How would I write that?

Community
  • 1
  • 1
Jeremy Holovacs
  • 22,480
  • 33
  • 117
  • 254

2 Answers2

4

You could use something like:

public static IEnumerable<int> GetIndices<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
    return items.Select( (item, index) => new { Item = item, Index = index })
                     .Where(p => predicate(p.Item))
                     .Select(p => p.Index);
}
hunter
  • 62,308
  • 19
  • 113
  • 113
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

Here’s the non-LINQ implementation:

public static IEnumerable<int> GetIndexes<T>(this IEnumerable<T> items, 
    Func<T, bool> predicate)
{
    int i = 0;

    foreach (T item in items)
    {
       if (predicate(item))
           yield return i;

       i++;
    }
}

In this case, this would probably be more efficient since it avoids the anonymous type initialization.

Douglas
  • 53,759
  • 13
  • 140
  • 188