tags:

views:

549

answers:

2

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= ?

+10  A: 

Don't use a query expression. Use the overload of Select which passes you an index:

var list = FileList.Select((file, index) => new { Index=index, Filename=file });

Jon Skeet
A: 
string[] values = { "a", "b", "c" };
int i = 0;
var t = from v in values
select new { Index = i++, Value = v};
GeekyMonkey
Why go to all that trouble instead of using the version that's provided by the framework?
Jon Skeet
Please don't ever do mutations within linq queries....
Justice
Why not!? It works. You have full control this way.I probably wouldn't do this myself, but that's the question that was asked.
GeekyMonkey
But if you run/invoke/trigger the query twice you'll get differnt IDs - I wouldnt mind if there was a ToArray on the end to hilight this...
Ruben Bartelink
Plus, with the new paralleling that can be applied to linq, you could have them out of order and even using the same numbers. Ouch!
mattdekrey
Valid points. I was just trying to give a simple answer to a simple question. The above code should be wrapped in a neat little function (or at least curly braces) that only allows the query to run once, and then "i" would go out of scope, and it should not be used with parallel link obviously.
GeekyMonkey