65.9K
CodeProject is changing. Read more.
Home

Generating sequential indices using LINQ

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Jan 16, 2011

CPOL
viewsIcon

20164

Many LINQ functions have a hidden parameter useful to generate or analyze sequential indices

Calculating index using index++.
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.
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.
words = new ObservableCollection<LookupItem>(
    "Hello world from LINQ".Split(" ".ToCharArray()).
    Where((word, index) => index < 100).
    Select((word, index) => new LookupItem { Caption = word, Index = index }));