2012-07-24 32 views
3

我有项目,我想将它们添加到字典中而不使用Add方法(因为它消耗了行数)。有没有什么办法将项目添加到字典一样在C#中不使用Add方法添加项目到字典

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

或像列表的AddRange方法。任何帮助将被高度讽刺。

+0

为什么你不”你想要更多的线? – Charlie 2012-07-24 03:54:50

回答

4

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}} 
}; 
+0

邦很感谢。 – ethicallogics 2012-07-24 04:01:58

2

引用您可以轻松地创建,做一个的AddRange为你的字典的扩展方法

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

     } 
    } 
} 
+0

非常感谢您的回复。 – ethicallogics 2012-07-24 04:10:14

+0

@ethicallogics从你的问题中,你不清楚你的意思是初始化 – 2012-07-24 04:11:49

1

很容易,因为

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

非常感谢回复。 – ethicallogics 2012-07-24 04:09:38