确定IQueryable中元素的位置

我有一个IQueryable,它按某种条件排序。 现在我想知道IQueryable中特定元素的位置。 是否有linq表达式来实现。 比如说IQueryable中有10个元素,第6个元素与条件匹配,我想得到数字6。

首先用索引选择每个项目,然后过滤项目,最后提取原始索引:

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; 

试验台:

 class Program { static void Main(string[] args) { var orderedList = new List { "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); } } 

输出:

 Index: 5 

你可以使用像query.TakeWhile(x => !matchesCondition(x)).Count() ,虽然它具有枚举前面的值的效果,这可能不是你想要的。

您还可以使用包含集合索引的“Where”函数的verson作为谓词函数的参数。 有关详细信息,请参阅MSDN 。

 var result = Enumerable.Range(0, 10).Where((x, i) => i == 6); 

如果没有第6个元素,该版本可能会导致空列表。 在迭代结果之前,这也不会评估where子句。