如何在LINQ查询语言中使用where / index?

是否有可能使用查询语言编写此…而不是方法链?

notifications.Where((n, index) => n.EventId == m_lastSelectedEventID) .Select((n, index) => new {Position = index}).FirstOrDefault(); 

谢谢,拉杜

不,我担心查询表达式语法不支持那些重载。

另一方面,如果在开始时使用Select过载一次创建具有索引和值的匿名类型,则可以在查询表达式中使用该对序列。 例如:

 var query = from pair in sequence.Select((value, index) => new { value, index }) where pair.index % 3 == 0 select string.Format("{0}: {1}", pair.index, pair.value); 

编辑:请注意,在您的示例代码中,您始终先过滤,然后获取结果序列中第一个条目的索引。 该索引将始终为0.如果您想在notifications实际找到所选ID的原始索引,我怀疑您真的想要:

 int? index = notifications.Select((n, index) => new { n, index }) .Where(pair => pair.n.EventId == m_lastSelectedEventID) .Select(pair => (int?) pair.index) .FirstOrDefault(); 

(如果找不到,那将返回nullNullable 。)