Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the position of an element in an IQueryable

I have a IQueryable which is ordered by some condition. Now I want to know the position of a particular element in that IQueryable. Is there a linq expression to get that. Say for example there are 10 elements in the IQueryable and the 6th element matches a condition, I want to get the number 6.

like image 510
San Avatar asked Dec 08 '09 19:12

San


1 Answers

First select each item with its index, then filter the items, and finally extract the original index:

var result = orderedList
    .Select((x, i) => new { Item = x, Index = i })
    .Where(itemWithIndex => itemWithIndex.Item.StartsWith("g"))
    .FirstOrDefault();

int index= -1;
if (result != null)
    index = result.Index;

Test bed:

class Program
{
    static void Main(string[] args)
    {
        var orderedList = new List<string>
        {
            "foo", "bar", "baz", "qux", "quux",
            "corge", "grault", "garply", "waldo",
            "fred", "plugh", "xyzzy", "thud"
        }.OrderBy(x => x);

        // bar, baz, corge, foo, fred, garply, grault,
        // plugh, quux, qux, thud, waldo, xyzzy
        // Find the index of the first element beginning with 'g'.

        var result = orderedList
            .Select((x, i) => new { Item = x, Index = i })
            .Where(itemWithIndex => itemWithIndex.Item.StartsWith("g"))
            .FirstOrDefault();

        int index= -1;
        if (result != null)
            index = result.Index;

        Console.WriteLine("Index: " + index);
    }
}

Output:

Index: 5
like image 92
Mark Byers Avatar answered Oct 19 '22 02:10

Mark Byers