How do you add an index field to Linq results

Viewed 38883

Lets say I have an array like this:

string [] Filelist = ...

I want to create an Linq result where each entry has it's position in the array like this:

var list = from f in Filelist
    select new { Index = (something), Filename = f};

Index to be 0 for the 1st item, 1 for the 2nd, etc.

What should I use for the expression Index= ?

3 Answers
string[] values = { "a", "b", "c" };
int i = 0;
var t = (from v in values
select new { Index = i++, Value = v}).ToList();

You cannot get an index using pure LINQ query expressions (those with from.. where.. select.. clauses).

However, this doesn't mean you have to completely give up on this LINQ query style.

You just have to get out of the LINQ query expression and use a .Select(item, index) method overload.

var newestExistingFilesWithIndexes = 
    (from f in Filelist
     // we love LINQ query expressions
     where f.Exists
     // and we use it anywhere possible
     orderby f.LastModified descending
     select f)
     // but sometimes we have to get out and use LINQ extension methods
    .Select((f, index) => new { Index = index, Filename = f.Fullname});

or suppose, you need to filter a list based on item index ...

var newestExistingFilesOnlyEvenIndexes = 
     // use the Select method overload to get the index
    (from f in Filelist.Select((file, index) => new { file, index })
     // only take item with an even index
     where f.index % 2 == 0
     where f.file.Exists
     orderby f.file.LastModified descending
     select f.file);
Related