I have a string array that I want to convert to a Dictionary
using Linq.
I want elements with a even index (including zero) to be keys and elements with an odd index to be values in the dictionary. I created a dictionary using a 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]);
}
//myDict -> { { "John", "A" },{"Luke","B"} }
And now I am curious how to do it with LINQ ToDictionary()
:
myDict = arr.ToDictionary();
You can put it like this (in case of Linq we can exploit Enumerable.Range
as a loop):
string[] arr = new string[] {
"John", "A",
"Luke", "B",
}
var myDict = Enumerable
.Range(0, arr.Length / 2)
.ToDictionary(i => arr[2 * i],
i => arr[2 * i + 1]);
Console.WriteLine(string.Join(Environment.NewLine, myDict));
Outcome:
[John, A]
[Luke, B]
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