Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ, iterators, selecting and projection

Tags:

c#

linq

What I would like to do is use the elegance of LINQ while maintaining an iterator....

essentially

Class A
{
  int Position;
  string Name;
}

if I have a list of strings, i want to project them into List<A> but have the Position be populated in the projection...

List<string> names; //filled with strings

something like

List<A> foo = (from s in names select s).ToList();

but have it also iterate over and populate Position..

is this possible?

{{Position:0,Name: "name1"},{Position:1, Name: "name2"}, {Position:2, Name: "name3"}....}
like image 634
E Rolnicki Avatar asked Dec 16 '08 22:12

E Rolnicki


1 Answers

You can do this:

    var listOfStrings = new List<string> {"name1", "name2", "name3", "name4"};
    var foo = listOfStrings.Select((value, position) => new {position, value}).ToList();

Position will be incremented as a 0-starting index, check the Select Method overload.

like image 153
Christian C. Salvadó Avatar answered Sep 20 '22 18:09

Christian C. Salvadó