user1955031
user1955031

Reputation: 11

list ToDictionary with a new generated key using Linq

I have a list of objects that I want to turn into a dictionary with a new index key. Here is a simple example:

Original:
"alpha"
"beta"
"charlie"

I want:
1, "alpha"
2, "beta"
3, "charlie"

I can solve it this way:

void Main()
{
    var slist = new List<string>();
    slist.Add("alpha");
    slist.Add("beta");
    slist.Add("charlie");

    int i=0;
    var v = slist.ToDictionary (s => i++ );

    slist.Dump();
    v.Dump();
}

Is it any shorter/smarter way to solve this? For example avoid int i = 0 in the line before the query?

Upvotes: 0

Views: 990

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460238

You can use the overload of Select to get the index.

var v = slist.Select((s,i) => new {s, i})
             .ToDictionary(x => x.i + 1,  x => x.s);

Upvotes: 2

lante
lante

Reputation: 7346

var v = slist.ToDictionary(s => slist.IndexOf(s) + 1);

Upvotes: 0

Related Questions