ToDictionary method in C#


The ToDictionary method is an extension method in C# and converts a collection into Dictionary.

Firstly, create a string array −

string[] str = new string[] {"Car", "Bus", "Bicycle"};

Now, use the Dictionary method to convert a collection to Dictionary −

str.ToDictionary(item => item, item => true);

Here is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      string[] str = new string[] {"Car", "Bus", "Bicycle"};
      // key and value under ToDictionary
      var d = str.ToDictionary(item => item, item => true);
      foreach (var ele in d) {
         Console.WriteLine("{0}, {1}", ele.Key, ele.Value);
      }
   }
}

Output

Car, True
Bus, True
Bicycle, True

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

672 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements