C# Example of getting the index of items in a LINQ Select query

    class Program
    {
        private static List<Book> _books  = new List<Book>
        {
            new Book {Id = 9999, Title = "Book A" },
            new Book {Id = 22, Title = "Book B" },
            new Book {Id = 3876, Title = "Book C" },
        };

        static void Main(string[] args)
        {
            // In the LINQ lambda the second parameter is the index 
            var bookList = Books.Select((b, i) => new { Index = i, Book = b }).ToList();

            foreach (var bookWithIndex in bookList)
            {
                Console.WriteLine(string.Format("Book Id: {0}, Title : {1}, Index: {2}", 
                    bookWithIndex.Book.Id, 
                    bookWithIndex.Book.Title, 
                    bookWithIndex.Index));
            }

            Console.ReadKey();
        }

        static IEnumerable<Book> Books
        {
            get
            {
                foreach (var book in _books)
                {
                    yield return book;
                }
            }
        }
    }

    public class Book
    { 
        public int Id { get; set; }
        public string Title { get; set; }
    }

Leave a comment