簡體   English   中英

如何在C#中向Dictionary添加多個值

[英]How to add multiple values to Dictionary in C#

如果我不想多次調用“.Add()”,那么向Dictionary添加多個值的最佳方法是什么? 編輯 :我想在啟動后填寫它! 字典中已有一些值!

而不是

    myDictionary.Add("a", "b");
    myDictionary.Add("f", "v");
    myDictionary.Add("s", "d");
    myDictionary.Add("r", "m");
    ...

我想做這樣的事情

 myDictionary.Add(["a","b"], ["f","v"],["s","d"]);

有這樣的方法嗎?

您可以使用花括號,但這僅適用於初始化:

var myDictionary = new Dictionary<string, string>
{
    {"a", "b"},
    {"f", "v"},
    {"s", "d"},
    {"r", "m"}
};

這就是所謂的“集合初始化”,並適用於任何ICollection<T>鏈接或字典此鏈接的任何其他集合型)。 實際上,它適用於任何實現IEnumerable並包含Add方法的對象類型:

class Foo : IEnumerable
{
    public void Add<T1, T2, T3>(T1 t1, T2 t2, T3 t3) { }
    // ...
}

Foo foo = new Foo
{
    {1, 2, 3},
    {2, 3, 4}
};

基本上這只是反復調用Add -method的語法糖。 初始化后,有幾種方法可以做到這一點,其中一種方法是手動調用Add -methods:

var myDictionary = new Dictionary<string, string>
    {
        {"a", "b"},
        {"f", "v"}
    };

var anotherDictionary = new Dictionary<string, string>
    {
        {"s", "d"},
        {"r", "m"}
    };

// Merge anotherDictionary into myDictionary, which may throw
// (as usually) on duplicate keys
foreach (var keyValuePair in anotherDictionary)
{
    myDictionary.Add(keyValuePair.Key, keyValuePair.Value);
}

或者作為擴展方法:

static class DictionaryExtensions
{
    public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> target, IDictionary<TKey, TValue> source)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (target == null) throw new ArgumentNullException("target");

        foreach (var keyValuePair in source)
        {
            target.Add(keyValuePair.Key, keyValuePair.Value);
        }
    }
}

var myDictionary = new Dictionary<string, string>
    {
        {"a", "b"},
        {"f", "v"}
    };

myDictionary.Add(new Dictionary<string, string>
    {
        {"s", "d"},
        {"r", "m"}
    });

這不是一個重復的問題,但你可能想要的是有一個Dictionary.AddRange()方法。 這就是為什么不存在的原因:

為什么Dictionary沒有AddRange?

“Range對於關聯容器沒有任何意義。”

但是將自己的.AddRange()方法編寫到Dictionary類可能是個好主意。 它本質上是一個.Add()調用的循環。

雖然問題已得到解答,但我很好奇是否有可能將類似集合初始化器的語法應用於已經初始化的字典,而沒有創建/開銷創建第二個字典以進行合並和丟棄。

您可以使用(濫用?) Collection Initializers 創建為現有Dictionary添加一系列值。 怎么樣? 通過創建一個幫助程序類來執行它:

public class AddRangeTo<TKey, TValue> : IEnumerable
{
    private readonly IDictionary<TKey, TValue> WrappedDictionary;

    public AddRangeTo(IDictionary<TKey, TValue> wrappedDictionary)
    {
        this.WrappedDictionary = wrappedDictionary;
    }

    public void Add(TKey key, TValue value)
    {
        this.WrappedDictionary.Add(key, value);
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotSupportedException();
    }
}

用法:

var myDictionary = new Dictionary<string, string>();

new AddRangeTo<string, string>(myDictionary)
{
    {"a", "b"},
    {"f", "v"},
    {"s", "d"},
    {"r", "m"}
};

請注意,這允許您使用類似的語法向字典添加條目,但是已經初始化的字典。 那種糟糕的部分是<string, string>泛型的重復,但是C#6.0並不是必需的。 (編輯:也就是說,在C#6中它看起來像new AddRangeTo(myDictionary) (編輯:此功能從C#6中new AddRangeTo(myDictionary)

盡管如此,我並不是真的建議這樣做。 這是奇怪的語法/用法與意想不到的副作用,我認為當他們遇到它時可能會讓其他人感到困惑。 但是如果你發現你實際上會使用它並使你的內部代碼更容易使用和維護,那么獎金!

你可以這樣做:

var myDict = new Dictionary<string, string>() 
{
    {"a", "aa"},
    {"b", "bb"},
    {"c", "cc"},
    {"d", "dd"}
};

您可以在初始化時像所有其他答案節目一樣進行,或者您可以將其與此技巧結合使用:

Dictionary<string, string> myDictionary = new Dictionary<string, string>();
Dictionary<string, string> secondDictionary = new Dictionary<string, string>()
{ 
    {"1", "a"}, 
    {"2", b"} 
};
myDictionary = myDictionary.Union(secondDictionary)
                           .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

您必須確保沒有重復的密鑰或者您將獲得異常(但這與Add方法相同)。

這將是一個簡單的谷歌搜索: http//msdn.microsoft.com/en-us/library/bb531208.aspx 無論如何......這是代碼:

Dictionary<string, string> myDictionary = new Dictionary<string, string>()
{
    { 'a', 'b' },
    { 'c', 'd' },
    { 'e', 'f' }
};

當然,您也可以編寫一個循環或其他東西來迭代您的值並每次調用.add()方法。

好吧,你可以初始化:

new Dictionary<string, string> { {"a","b"}, {"f","v"},{"s","d"} }

這稱為集合初始值設定項。 如果要將多個項目添加到現有字典中,可以編寫方法。

這可以通過主代碼路徑完成,允許您使用擴展方法減少發生的混亂。

public static class DictionaryExtensions
{
  public static IDictionary<TKey,TValue> AddRange<TKey,TValue>(
               this IDictionary<TKey,TValue> source,
               params  KeyValuePair<TKey,TValue>[] items)
  {
    foreach (var keyValuePair in items)
    {
      source.Add(keyValuePair.Key, keyValuePair.Value);
    }
    return source;
  }
}

myDictionary = new Dictionary(){{“a”,2)},{“b”,3},};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM