How to use index/position with Where in LINQ query language? [duplicate]
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
No, query expression syntax doesn't have support for those overloads I'm afraid.
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);
EDIT: 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();
(That will return a Nullable<int>
of null
if not found.)
精彩评论