0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C# 自分用メモ その2 Dictionary は ソートされない

Last updated at Posted at 2024-06-21

1. はじめに

私はいい歳したC/C++屋さんなのですが、必要に迫られてC#を触っています。そんなこんなで「ん~これはハマりそうだな」と思った事を記録しておきます。自分用メモ。

実行結果は以下のようにソートされていません。C++で言う所の unordered_map みたいだね。

[3:2]
[1:2]
[4:1]
[5:3]
[9:1]
[2:1]
[6:1]

2.というわけでコード

Program.cs
using System;
using System.Collections.Generic;

namespace DictionaryTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // key, カウンタ
            Dictionary<int, int> dicTest = new Dictionary<int, int>();

            Func(dicTest, 3);
            Func(dicTest, 1);
            Func(dicTest, 4);
            Func(dicTest, 1);
            Func(dicTest, 5);
            Func(dicTest, 9);
            Func(dicTest, 2);
            Func(dicTest, 6);
            Func(dicTest, 5);
            Func(dicTest, 3);
            Func(dicTest, 5);

            foreach (KeyValuePair<int, int> dicItem in dicTest)
            {
                Console.WriteLine("[{0}:{1}]", dicItem.Key, dicItem.Value);
            }
        }

        static void Func(Dictionary<int, int> dic, int n)
        {
            if(!dic.ContainsKey(n))
            {
                dic[n] = 1;
            }
            else
            {
                dic[n]++;
            }
        }
    }
}

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?