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
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) .
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.
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.
Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With