tags:

views:

52

answers:

1

Is there anu posibility 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

+2  A: 

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
Do you have any idea about the performance if you invert where and select? Is there any difference?
Radu D
@Radu: Well, it'll give different *results* apart from anything else. I'll edit my question to explain.
Jon Skeet
Thnaks ... very good observation :)
Radu D