3

項目があり、Add メソッドを使用せずに Dictionary に追加したい (行数を消費するため)。次のような項目を Dictionary に追加する方法はありますか

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

またはリストの AddRange メソッドのように。どんな助けでも非常に高く評価されます。

4

3 に答える 3

4

ここから引用

 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}}
};
于 2012-07-24T03:50:53.713 に答える
3

辞書の 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();

        }
    }
}
于 2012-07-24T03:52:20.840 に答える
2

それは簡単です

var dictionary = new Dictionary<int, string>() {{1, "firstString"},{2,"secondString"}};
于 2012-07-24T03:53:28.313 に答える