Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Generating sequential indices using LINQ

5.00/5 (2 votes)
17 Jan 2011CPOL 20.1K  
Many LINQ functions have a hidden parameter useful to generate or analyze sequential indices
Calculating index using index++.

C#
int index = 0;
words = new ObservableCollection<LookupItem>(
    // trick number 1: converting string into char[]
    from word in "Hello world from LINQ".Split(" ".ToCharArray())
    select new LookupItem { Caption = word, Index = index++ }));


The same using built-in LINQ functionality.

C#
words = new ObservableCollection<LookupItem>(
    "Hello world from LINQ".Split(" ".ToCharArray()).
    // trick number 2: generating sequential numbers using LINQ
    Select((word, index) => new LookupItem { Caption = word, Index = index }));


Other useful LINQ functions having second form with index are TakeWhile, SkipWhile and Where.

C#
words = new ObservableCollection<LookupItem>(
    "Hello world from LINQ".Split(" ".ToCharArray()).
    Where((word, index) => index < 100).
    Select((word, index) => new LookupItem { Caption = word, Index = index }));

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)