Reputation: 11
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
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