简体   繁体   English

不使用C#中的Add方法将项添加到Dictionary

[英]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). 我有项目,我想将它们添加到Dictionary而不使用Add方法(因为它消耗了多少行)。 Is there any way to add items to Dictionary like 有没有办法将项目添加到词典中

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

or like AddRange Method in List. 或者像列表中的AddRange方法。 Any help will be highly appericiated. 任何帮助都会得到很高的评价。

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

You can easily create an extension method that does an AddRange for your dictionary 您可以轻松创建一个扩展方法,为您的字典执行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();

        }
    }
}

它就像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM