Friday, 29 July 2011

How to Get the Index Position of the LINQ Query Results

Select  and SelectMany  expose an overload that surfaces the index position (starting at zero) for each returned element in the Select projection. It is surfaced as an overloaded parameter argument of the selector lambda expression and is only accessible using the extension method query syntax(Lamda Expression). The following sample code demonstrates how to access and use the index position value in a Select projection.
List<CallLog> callLog = CallLog.SampleData();
var q = callLog.GroupBy(g => g.Number)
.OrderByDescending(g => g.Count())
.Select((g, index) => new
{
number = g.Key,
rank = index + 1, //one is added because it is zero based index
count = g.Count()
});

No comments:

Post a Comment