How do you add an index field to Linq results
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= ?
Solution 1:
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 });
Solution 2:
string[] values = { "a", "b", "c" };
int i = 0;
var t = (from v in values
select new { Index = i++, Value = v}).ToList();