How to convert an array to a dictionary using LINQ

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]);
}

//myDict -> { { "John", "A" },{"Luke","B"} }

And now I'm curious how to do this with LINQ ToDictionary():

myDict = arr.ToDictionary();
+4
source share
2 answers

This can be done like this (in the case of Linq, we can use it Enumerable.Rangeas 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));

Result:

[John, A]
[Luke, B]
+4
source

You can group by index divided by 2. Try this code:

string[] arr = new string[4];
arr[0] = "John";
arr[1] = "A";
arr[2] = "Luke";
arr[3] = "B";

var dict = arr.Select((s, i) => new {s, i})
    .GroupBy(x => x.i / 2)
    .ToDictionary(g => g.First().s, g => g.Last().s);
+4
source

Source: https://habr.com/ru/post/1693724/


All Articles