Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use index/position with Where in LINQ query language? [duplicate]

Tags:

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

like image 717
Radu D Avatar asked Oct 29 '10 07:10

Radu D


People also ask

How do I find duplicate records in LINQ?

The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to: var query = lst. GroupBy(x => x) .

How do you find the index of an element in LINQ?

LINQ does not have an IndexOf method. So to find out index of a specific item we need to use FindIndex as int index = List. FindIndex(your condition); 0.

On which datasources do LINQ queries work?

In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, . NET collections, and any other format for which a LINQ provider is available.

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.


1 Answers

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

like image 69
Jon Skeet Avatar answered Sep 27 '22 18:09

Jon Skeet