如何使用索引/位置与凡在LINQ查询语言?如何使用、索引、位置、语言

2023-09-02 10:38:23 作者:超能力i的人

有没有写这个使用的查询语言......没有办法链中的任何可能性?

Is there any possibility to write this using query language ... not method chain?

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

谢谢, 拉杜

Thanks, Radu

推荐答案

没有,查询前pression语法不具备这些重载恐怕支持。

No, query expression syntax doesn't have support for those overloads I'm afraid.

在另一方面,如果你明确的使用选择超载的一次的在开始创建匿名类型在,你就可以用对的序列内查询前的指数值pression。例如:

On the other hand, if you use the Select overload explicitly once at the start to create an anonymous type with the index and value in, you can then use that sequence of pairs within a query expression. For example:

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);

编辑:请注意,您的样品code,你总是过滤,然后再考虑在结果的序列中的第一个条目的索引。该索引将始终为0。如果你想真正找到在的通知选定的ID的原的指数,我怀疑你真正想要的:

Note that in your sample code, you're always filtering first and then taking the index of the first entry in the result sequence. That index will always be 0. If you want to actually find the original index of the selected ID within notifications, I suspect you really want:

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

(这将返回可空< INT> 如果没有找到)