30

辞書オブジェクトを作成しました

Dictionary<string, List<string>> dictionary =
    new Dictionary<string,List<string>>();

特定の単一キーの文字列のリストに文字列値を追加したいと思います。キーがまだ存在しない場合は、新しいキーを追加する必要があります。List<string>は事前定義されていません。つまり、リストオブジェクトを作成してから、に提供していませんdictionary.Add("key",Listname)。このリストオブジェクトを動的に作成し、dictionary.Add("key",Listname)このリストに文字列を追加する方法。100個のキーを追加する必要がある場合、命令を実行する前に100個のリストを作成する必要がdictionary.Addありますか?また、このリストの内容をペデファインする必要がありますか?

ありがとうございました。

4

12 に答える 12

38

更新:TryGetValueリストがある場合に1つのルックアップのみを実行するために使用して存在を確認します。

List<int> list;

if (!dictionary.TryGetValue("foo", out list))
{
    list = new List<int>();
    dictionary.Add("foo", list);
}

list.Add(2);


オリジナル: 存在を確認して一度追加してから、辞書にキー入力してリストを取得し、通常どおりリストに追加します。

var dictionary = new Dictionary<string, List<int>>();

if (!dictionary.ContainsKey("foo"))
    dictionary.Add("foo", new List<int>());

dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);

またはList<string>あなたの場合のように。

余談ですが、などの動的コレクションに追加するアイテムの数がわかっている場合List<T>は、初期リスト容量を使用するコンストラクターを優先してくださいnew List<int>(100);

これにより、いっぱいになり始めるたびに小さなチャンクを取得するのではなく、指定された容量を満たすために必要なメモリを事前に取得します100個のキーがあることがわかっている場合は、辞書でも同じことができます。

于 2012-04-10T13:37:11.193 に答える
9

私があなたが望むものを理解した場合:

dictionary.Add("key", new List<string>()); 

後で...

dictionary["key"].Add("string to your list");
于 2012-04-10T13:37:33.343 に答える
6
Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>();

foreach(string key in keys) {
    if(!dictionary.ContainsKey(key)) {
        //add
        dictionary.Add(key, new List<string>());
    }
    dictionary[key].Add("theString");
}

キーが存在しない場合は、新しいキーListが追加されます(if内)。Listそれ以外の場合はキーが存在するため、そのキーの下に新しい値を追加するだけです。

于 2012-04-10T13:41:12.840 に答える
4

から派生したマルチマップの私の実装を使用できますDictionary<K, List<V>>。それは完璧ではありませんが、それは良い仕事をします。

/// <summary>
/// Represents a collection of keys and values.
/// Multiple values can have the same key.
/// </summary>
/// <typeparam name="TKey">Type of the keys.</typeparam>
/// <typeparam name="TValue">Type of the values.</typeparam>
public class MultiMap<TKey, TValue> : Dictionary<TKey, List<TValue>>
{

    public MultiMap()
        : base()
    {
    }

    public MultiMap(int capacity)
        : base(capacity)
    {
    }

    /// <summary>
    /// Adds an element with the specified key and value into the MultiMap. 
    /// </summary>
    /// <param name="key">The key of the element to add.</param>
    /// <param name="value">The value of the element to add.</param>
    public void Add(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            valueList.Add(value);
        } else {
            valueList = new List<TValue>();
            valueList.Add(value);
            Add(key, valueList);
        }
    }

    /// <summary>
    /// Removes first occurence of an element with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the element to remove.</param>
    /// <param name="value">The value of the element to remove.</param>
    /// <returns>true if the an element is removed;
    /// false if the key or the value were not found.</returns>
    public bool Remove(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            if (valueList.Remove(value)) {
                if (valueList.Count == 0) {
                    Remove(key);
                }
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// Removes all occurences of elements with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the elements to remove.</param>
    /// <param name="value">The value of the elements to remove.</param>
    /// <returns>Number of elements removed.</returns>
    public int RemoveAll(TKey key, TValue value)
    {
        List<TValue> valueList;
        int n = 0;

        if (TryGetValue(key, out valueList)) {
            while (valueList.Remove(value)) {
                n++;
            }
            if (valueList.Count == 0) {
                Remove(key);
            }
        }
        return n;
    }

    /// <summary>
    /// Gets the total number of values contained in the MultiMap.
    /// </summary>
    public int CountAll
    {
        get
        {
            int n = 0;

            foreach (List<TValue> valueList in Values) {
                n += valueList.Count;
            }
            return n;
        }
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific
    /// key / value pair.
    /// </summary>
    /// <param name="key">Key of the element to search for.</param>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            return valueList.Contains(value);
        }
        return false;
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific value.
    /// </summary>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TValue value)
    {
        foreach (List<TValue> valueList in Values) {
            if (valueList.Contains(value)) {
                return true;
            }
        }
        return false;
    }

}

このAddメソッドは、キーがすでに存在するかどうかを確認することに注意してください。キーが新しい場合は、新しいリストが作成され、値がリストに追加され、リストがディクショナリに追加されます。キーがすでに存在する場合は、新しい値が既存のリストに追加されます。

于 2012-04-10T13:39:23.350 に答える
3

NameValuedCollectionを使用します。

良い出発点はここにあります。リンクから直接。

System.Collections.Specialized.NameValueCollection myCollection
    = new System.Collections.Specialized.NameValueCollection();

  myCollection.Add(“Arcane”, “http://arcanecode.com”);
  myCollection.Add(“PWOP”, “http://dotnetrocks.com”);
  myCollection.Add(“PWOP”, “http://dnrtv.com”);
  myCollection.Add(“PWOP”, “http://www.hanselminutes.com”);
  myCollection.Add(“TWIT”, “http://www.twit.tv”);
  myCollection.Add(“TWIT”, “http://www.twit.tv/SN”);
于 2012-04-10T14:31:39.020 に答える
2

他のほとんどの回答とほぼ同じですが、これが最も効率的で簡潔な実装方法だと思います。他のいくつかのソリューションが示しているように、TryGetValueを使用すると、ContainsKeyを使用してディクショナリにインデックスを再作成するよりも高速です。

void Add(string key, string val)
{
    List<string> list;

    if (!dictionary.TryGetValue(someKey, out list))
    {
       values = new List<string>();
       dictionary.Add(key, list);
    }

    list.Add(val);
}
于 2012-04-10T13:45:57.470 に答える
0

文字列を追加するときは、キーがすでに存在するかどうかによって異なる方法で追加します。valueキーの文字列を追加するにはkey

List<string> list;
if (dictionary.ContainsKey(key)) {
  list = dictionary[key];
} else {
  list = new List<string>();
  dictionary.Add(ley, list);
}
list.Add(value);
于 2012-04-10T13:38:33.063 に答える
0

辞書を使用する代わりに、ILookupに変換してみませんか?

var myData = new[]{new {a=1,b="frog"}, new {a=1,b="cat"}, new {a=2,b="giraffe"}};
ILookup<int,string> lookup = myData.ToLookup(x => x.a, x => x.b);
IEnumerable<string> allOnes = lookup[1]; //enumerable of 2 items, frog and cat

ILookupは、キーごとに複数の値を許可する不変のデータ構造です。異なる時間にアイテムを追加する必要がある場合は、おそらくあまり使用されませんが、すべてのデータを事前に用意している場合は、これが間違いなく進むべき道です。

于 2012-04-10T13:46:58.160 に答える
0

1つの答えの多くのバリエーションがあります:)私のものは別のものであり、実行するための快適な方法として拡張メカニズムを使用しています(便利です):

public static void AddToList<T, U>(this IDictionary<T, List<U>> dict, T key, U elementToList)
{

    List<U> list;

    bool exists = dict.TryGetValue(key, out list);

    if (exists)
    {
        dict[key].Add(elementToList);
    }
    else
    {
        dict[key] = new List<U>();
        dict[key].Add(elementToList);
    }

}

次に、次のように使用します。

Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();

dict.AddToList(4, "test1");
dict.AddToList(4, "test2");
dict.AddToList(4, "test3");

dict.AddToList(5, "test4");
于 2013-06-27T14:17:57.433 に答える
0

必要なことを正確に実行するクラスを含むNuGetパッケージのMicrosoftExperimentalCollectionsがあります。MultiValueDictionary

これは、パッケージの作成者のブログ投稿で、さらに詳しく説明しています

気になる方は、こちらのブログ投稿をご覧ください。

使用例:

MultiDictionary<string, int> myDictionary = new MultiDictionary<string, int>();
myDictionary.Add("key", 1);
myDictionary.Add("key", 2);
myDictionary.Add("key", 3);
//myDictionary["key"] now contains the values 1, 2, and 3
于 2015-10-01T12:33:24.390 に答える
0

辞書の既存のキーにリストを追加しようとして、次の解決策に到達しました。

Dictionary<string,List<string>> NewParent = new Dictionary<string,List<string>>();
child = new List<string> ();
child.Add('SomeData');
NewParent["item1"].AddRange(child);

例外は表示されず、以前の値が置き換えられることはありません。

于 2015-12-01T11:33:38.757 に答える
0

ConcurrentDictionaryのAddOrUpdateを使用してこれを行う「1つのコマンドライン」の方法があります。

using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
 
...

var dictionary = new ConcurrentDictionary<string, IEnumerable<string>>();
var itemToAdd = "item to add to key-list";

dictionary.AddOrUpdate("key", new[]{itemToAdd}, (key,list) => list.Append(itemToAdd));

// If "key" doesn't exist, creates it with a list containing itemToAdd as value
// If "key" exists, adds item to already existent list (third parameter)
于 2021-03-10T22:01:27.560 に答える