Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array to a dictionary using LINQ

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();
like image 979
Slaven Tojic Avatar asked Dec 24 '22 09:12

Slaven Tojic


1 Answers

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]
like image 152
Dmitry Bychenko Avatar answered Jan 13 '23 15:01

Dmitry Bychenko