dthy
@dthy (dorrrothy)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

辞書 Keyが重複している場合Valueに加算

Q&A

Closed

左の文字がKey 右の数字がvalue
Keyが同じならValueを足す処理をしたいです。

入力例   
A 2      
B 3
A 1

出力例
A 3
B 3

    var dic = new Dictionary<string, int>();
    int n = int.Parse(Console.ReadLine()); //n=3

    for(int i = 0; i < n; i++)
    {
        var x = Console.ReadLine().Split(' ');
        if (dic.ContainsKey(x[0]))
        {
            //重複しているKeyのValueにx[1]を足したい
        }
        else
        {
            dic.Add(x[0], int.Parse(x[1]));//重複していないならそのままAdd
        }
    }

まだあまり辞書に触れていないのでこういう書き方のがわかりやすい
など改善方法もあれば教えていただきたいです。

0

2Answer

数字の Parse は先にやっておきたいところですね。

var x = Console.ReadLine().Split(' ');
if (x.Length < 2 || int.TryParse(x[1], out int value) == false)
  continue;

if (dic.ContainsKey[x[0]])
   dic[x[0]] += value;
else
   dic.Add(x[0], value);

後は好みで、原則加算、なければキーを追加してから、という手段にするとか。

var x = Console.ReadLine().Split(' ');
if (x.Length < 2 || int.TryParse(x[1], out int value) == false)
  continue;

if (!dic.ContainsKey[x[0]])
   dic.Add(x[0], 0);

dic[x[0]] += value;
0Like

Dictionary型はは文字列等でも指定できるので
成功判定内を以下にすればよいと思います

if (dic.ContainsKey(x[0]))
{
    if (int.TryParse(x[1], out int res))
        dic[x[0]] += res;
}

0Like

Your answer might help someone💌