3

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.

2
  • How come you don't want more lines? Commented Jul 24, 2012 at 3:54
  • 1
    If it is not for initialization, you can simply use dictionaryObject[key] = value;. Commented Jul 24, 2019 at 10:23

3 Answers 3

4

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}} }; 
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

@ethicallogics From your question it wasn't clear whether you meant initialization
3

it's as easy as

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.