C# 在LINQ查询语言中,如何将索引/位置与Where一起使用?

C# 在LINQ查询语言中,如何将索引/位置与Where一起使用?,c#,.net,linq,C#,.net,Linq,有没有可能用查询语言写这个。。。不是方法链 notifications.Where((n, index) => n.EventId == m_lastSelectedEventID) .Select((n, index) => new {Position = index}).FirstOrDefault(); 谢谢, Radu不,恐怕查询表达式语法不支持这些重载 另一方面,如果在开始时显式使用Select重载创建索引和值为的匿名类型,则可以在查询表达式

有没有可能用查询语言写这个。。。不是方法链

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

不,恐怕查询表达式语法不支持这些重载

另一方面,如果在开始时显式使用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。如果您想在
通知
中实际查找所选ID的原始索引,我怀疑您确实想要:

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

(如果未找到,将返回
null
null

为什么?另外,这看起来很像输出是
AnonymousClass1{Position=1}
NULL
如果您反转where并选择,您对性能有什么想法吗?有什么不同吗?@Radu:嗯,除了其他任何东西,它会给出不同的结果。我将编辑我的问题以进行解释。另一种方式代替
int?
…Where(…)。选择(p=>I.index)。DefaultIfEmpty(-1)。First()
@Radu D-我这样想。在我使用Select的那一刻,需要一些我可以选择的东西。它将由select之前出现的查询部分定义。