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:
//(1,a)(2,b)(3,c)
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?
You can use the overload of Select
that projects the index to fill an anonymous 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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With