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?
There's no ToDictionary
method that gives this in a single call, as there are no overloads that provide the index, but you can use the Select
overload which accepts a Func<T, int, TResult>
:
var dictionary = list.Select((value, index) => new { value, index })
.ToDictionary(pair => pair.index, pair => pair.value);
Or in C# 7, avoiding creating a bunch of heap-allocated objects using ValueTuple
:
var dictionary = list.Select((v, i) => (value: v, index: i))
.ToDictionary(pair => pair.index, pair => pair.value);
As of C# 7.1 point release, you can use the inferred ValueTuple
literal expression:
var dictionary = list.Select((value, index) => (value, index))
.ToDictionary(pair => pair.index, pair => pair.value);
(As noted by Tim, you'll need to adjust the index by 1 to get the original requested output.)
See more on this question at Stackoverflow