キー値のペアに文字列とint値を格納しています。キー値のペアの既存の値を見つける
var list = new List<KeyValuePair<string, int>>();
私が代わりに新しいキーを追加することの価値にそれを追加する必要が存在する場合(キー)文字列はすでに、リスト内に存在するかどうかを確認する必要がありますが追加。
確認と追加の方法は?
キー値のペアに文字列とint値を格納しています。キー値のペアの既存の値を見つける
var list = new List<KeyValuePair<string, int>>();
私が代わりに新しいキーを追加することの価値にそれを追加する必要が存在する場合(キー)文字列はすでに、リスト内に存在するかどうかを確認する必要がありますが追加。
確認と追加の方法は?
リストの代わりにあなたがDictionaryを使用して確認することができます使用します、キーを探します。 単純にハッシュテーブルを使用できます。
あなたのニーズは正確にDictionary
のデザインを記述していますか?
Dictionary<string, string> openWith =
new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
地図は非常にJavaの言葉です; p – leppie
@leppie yup、それを固定しました。私はC++/Javaの世界からもっとです。 –
C#に相当するマップ? – Olivarsham
ジクローナルを使用してください。 Dictionary in C#と私はあなたがチェックしDictonary in .net
Dictionary<string, int> dictionary =
new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
この記事を読むことをお勧めします。それはcontains keyその後、既存のキー
int newValue = 10;
Dictionary<string, int> dictionary = new Dictionary<string, int>();
if (dictionary.ContainsKey("key"))
dictionary["key"] = dictionary["key"] + newValue;
リストを使用する必要がある場合は、foreachの必要があり、リストに新しい値を追加する場合にContainsKeyはContainsKey
if (dictionary.ContainsKey("key"))
dictionary["key"] = dictionary["key"] + yourValue;
確かに、あなたの場合は辞書が望ましいです。変更不可能なので、KeyValue<string,int>
クラスの値を変更することはできません。
でも、まだList<KeyValuePair<string, int>>();
を使用したい場合でも。 IEqualityComparer<KeyValuePair<string, int>>
を使用できます。コードは同じようになります。
public class KeyComparer : IEqualityComparer<KeyValuePair<string, int>>
{
public bool Equals(KeyValuePair<string, int> x, KeyValuePair<string, int> y)
{
return x.Key.Equals(y.Key);
}
public int GetHashCode(KeyValuePair<string, int> obj)
{
return obj.Key.GetHashCode();
}
}
そして、良い方法は聞こえるしない
var list = new List<KeyValuePair<string, int>>();
string checkKey = "my string";
if (list.Contains(new KeyValuePair<string, int>(checkKey, int.MinValue), new KeyComparer()))
{
KeyValuePair<string, int> item = list.Find((lItem) => lItem.Key.Equals(checkKey));
list.Remove(item);
list.Add(new KeyValuePair<string, int>("checkKey", int.MinValue));// add new value
}
のように入って、それを使用しています。
この情報が役に立ちます。
だから、なぜ「辞書」を使用しないのですか? – leppie
'KeyValuePair'は不変であることに注意してください。既存のエントリを削除し、値を更新するたびに新しいエントリを作成する必要があります。だからこそ、「辞書」が答えに与えられているよりはるかに優れているのです。 –
mellamokb
ありがとう、私は辞書と一緒に行きます。 – Olivarsham