I have a string array that I want to convert to Dictionaryusing Linq. I want elements with an even index (including zero) to be keys , and elements with an odd index to be values in a dictionary. I created a dictionary with for loop:
string[] arr = new string[4];
arr[0] = "John";
arr[1] = "A";
arr[2] = "Luke";
arr[3] = "B";
Dictionary<string, string> myDict = new Dictionary<string, string>();
for (int i = 0; i < arr.Length - 1; i += 2)
{
myDict.Add(arr[i], arr[i + 1]);
}
And now I'm curious how to do this with LINQ ToDictionary():
myDict = arr.ToDictionary();
source
share