yo chauhan
yo chauhan

Reputation: 12315

Adding items to Dictionary without using Add method in C#

I have items and I want to add them to Dictionary Without using Add method (because it consumes number of lines). Is there any way to add items to Dictionary like

new List<string>() { "P","J","K","L","M" };

or like AddRange Method in List. Any help will be highly appericiated.

Upvotes: 3

Views: 6037

Answers (3)

Konstantin Chernov
Konstantin Chernov

Reputation: 1936

it's as easy as

var dictionary = new Dictionary<int, string>() {{1, "firstString"},{2,"secondString"}};

Upvotes: 3

parapura rajkumar
parapura rajkumar

Reputation: 24433

You can easily create an extension method that does an AddRange for your dictionary

namespace System.Collections.Generic
{
    public static class DicExt
    {
        public static void AddRange<K, V>(this Dictionary<K, V> dic, IEnumerable<K> keys, V v)
        {
            foreach (var k in keys)
                dic[k] = v;
        }
    }
}

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            var list  = new List<string>() { "P", "J", "K", "L", "M" };
            var dic = new Dictionary<string, bool>();

            dic.AddRange(list, true);


            Console.Read();

        }
    }
}

Upvotes: 3

tsukimi
tsukimi

Reputation: 1645

Referenced from here

 Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
 {
   { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
   { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
   { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};

Upvotes: 4

Related Questions