确定在一个IQueryable一个元件的位置 [英] Determine the position of an element in an IQueryable

查看:281
本文介绍了确定在一个IQueryable一个元件的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有被一些条件下令IQueryable的。
现在我想知道在IQueryable的特定元素的位置。
是否有一个LINQ表达式来获取。
说,例如有在IQueryable的10个元素和第六元素相匹配的情况下,我想要得到的6号。

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.

推荐答案

首先选择每个项目有它的索引,然后筛选的项目,最后提取原始指数:

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

这篇关于确定在一个IQueryable一个元件的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆