26

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

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
Radu D
  • 3,505
  • 9
  • 42
  • 69
  • 1
    Why? Plus this looks a lot like the output is `AnonymousClass1 { Position = 1 }` or `NULL` – cjk Oct 29 '10 at 07:20

1 Answers1

47

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Do you have any idea about the performance if you invert where and select? Is there any difference? – Radu D Oct 29 '10 at 07:34
  • @Radu: Well, it'll give different *results* apart from anything else. I'll edit my question to explain. – Jon Skeet Oct 29 '10 at 07:38
  • Another way instead of the `int?`: `...Where(...).Select(p => i.index).DefaultIfEmpty(-1).First()`. – Tim Schmelter Jan 30 '15 at 10:53
  • @Radu D - I think about it this way. In the moment I use Select there will need to be something I can select from. It'll be defined by the part of the query that appears before select. – Mariusz Jun 07 '18 at 08:59