c0rd c0rd - 1 year ago 91
C# Question

Selecting List<string> into Dictionary with index

I have a List

List<string> sList = new List<string>() { "a","b","c"};

And currently I am selecting this into a dictionary the following structure:

Dictionary<int, string> dResult = new Dictionary<int, string>();
for(int i=0;i< sList.Count;i++)
dResult.Add(i, sList[i]);

but with Linq I've seen some slimmer way like
ToDictionary((x,index) =>

How is the correct syntax or how can this be solved within one line?

Answer Source

You can use the overload of Select that projects the index to fill an anymous type:

Dictionary<int, string> dResult = sList
    .Select((s, index) => new { s, index })
    .ToDictionary(x => x.index, x => x.s);

That is the same as what your code does. If you instead want the result you've commented: (1,a)(2,b)(3,c)) you have to add +1 so ToDictionary(x => x.index+1, x => x.s).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download