Reputation: 12315
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
Reputation: 1936
it's as easy as
var dictionary = new Dictionary<int, string>() {{1, "firstString"},{2,"secondString"}};
Upvotes: 3
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
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