Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 3. Writing Basic Queries > How to Get the Index Position of the Results

How to Get the Index Position of the 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. Listing 3-9 demonstrates how to access and use the index position value in a Select projection. As shown in Output 3-6, this example simply adds a ranking number for each select result string.

Listing 3-9. A zero-based index number is exposed by the Select and SelectMany operators—see Output 3-6

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,
                   count = g.Count()
               });

foreach (var c in q)
    Console.WriteLine(
        "Rank {0} - {1}, called {2} times.",
        c.rank, c.number, c.count);


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial