【问题标题】:Adding items to Dictionary without using Add method in C#将项目添加到字典而不使用 C# 中的 Add 方法
【发布时间】:2012-07-24 03:45:57
【问题描述】:

我有项目,我想在不使用 Add 方法的情况下将它们添加到 Dictionary(因为它会消耗行数)。有什么方法可以将项目添加到字典中

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

或者像 List 中的 AddRange 方法。任何帮助都将受到高度重视。

【问题讨论】:

  • 你为什么不想要更多的行?
  • 如果不是为了初始化,可以简单的使用dictionaryObject[key] = value;

标签: c# dictionary


【解决方案1】:

引用自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}}
};

【讨论】:

    【解决方案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();
    
            }
        }
    }
    

    【讨论】:

    • @ethicallogics 从你的问题来看,不清楚你的意思是否是初始化
    【解决方案3】:

    就这么简单

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

    【讨论】:

      猜你喜欢
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多