Thursday, February 17, 2011

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

From stackoverflow
  • 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 });

  • string[] values = { "a", "b", "c" };
    int i = 0;
    var t = from v in values
    select new { Index = i++, Value = v};
    
    Jon Skeet : Why go to all that trouble instead of using the version that's provided by the framework?
    Justice : Please don't ever do mutations within linq queries....
    GeekyMonkey : 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.
    Ruben Bartelink : 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...
    mattdekrey : 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!
    GeekyMonkey : 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.

0 comments:

Post a Comment