連想配列

C:\DATA\C#\BAT>Rensou
Daisy => 72
Eliza => 78
Becky => 85
Alice => 95
Cindy => 100
C# で連想配列を使います。

前田稔(Maeda Minoru)の超初心者のプログラム入門

プログラムの説明

  1. フォルダーに次のファイルを格納して下さい。
    /*★ 連想配列     前田 稔 ★*/
    using System;
    using System.Collections.Generic;
    using System.Linq;
    class DictionaryTest
    {   static void Main()
        {   Dictionary<string, int> dic = new Dictionary<string, int>()
            {   { "Becky", 85 },
                { "Daisy", 72 },
                { "Alice", 95 },
                { "Eliza", 78 },
                { "Cindy", 100 },
            };
            var sorted = dic.OrderBy((x) => x.Value);  //昇順
    
            foreach(var v in sorted)
            {   Console.WriteLine(v.Key + " => " + v.Value);  }
        }
    }
    
  2. 本来C#には連想配列はありませんが Dictionary を使って同様の機能を実現します。
    Dictionary<string, int> dic = で string と int をキーと値にした Dictionary(連想配列)を定義します。
    dic には初期値として5組のペアーが格納されています。
        {   Dictionary<string, int> dic = new Dictionary<string, int>()
            {   { "Becky", 85 },
                { "Daisy", 72 },
                { "Alice", 95 },
                { "Eliza", 78 },
                { "Cindy", 100 },
            };
    
  3. dic を Value(値)をキーにして昇順にソートして foreach で印字します。
            var sorted = dic.OrderBy((x) => x.Value);  //昇順
    
            foreach(var v in sorted)
            {   Console.WriteLine(v.Key + " => " + v.Value);  }
        }
    }
    
  4. 印字結果は次のようになります。
    Daisy => 72
    Eliza => 78
    Becky => 85
    Alice => 95
    Cindy => 100
    

データの追加とキーでソート

  1. フォルダーに次のファイルを格納して下さい。
    /*★ 連想配列     前田 稔 ★*/
    using System;
    using System.Collections.Generic;
    using System.Linq;
    class DictionaryTest
    {   static void Main()
        {   Dictionary<string, int> dic = new Dictionary<string, int>()
            {   { "Becky", 85 },
                { "Daisy", 72 },
                { "Alice", 95 },
                { "Eliza", 78 },
                { "Cindy", 100 },
            };
    
            dic.Add("Key3", 30);
            dic.Add("Key1", 10);
            dic.Add("Key2", 20);
            var sorted = dic.OrderByDescending((x) => x.Key);  //降順
    
            foreach(var v in sorted)
            {   Console.WriteLine(v.Key + " => " + v.Value);  }
        }
    }
    
  2. 初期値として5組のペアーを格納した dic に三件のデータを追加します。
            dic.Add("Key3", 30);
            dic.Add("Key1", 10);
            dic.Add("Key2", 20);
    
  3. dic を Key(キー)を降順にソートします。
            var sorted = dic.OrderByDescending((x) => x.Key);  //降順
    
  4. foreach で印字します。
            foreach(var v in sorted)
            {   Console.WriteLine(v.Key + " => " + v.Value);  }
        }
    
  5. キーで降順にソートしたので、印字結果は次のようになります。
    Key3 => 30
    Key2 => 20
    Key1 => 10
    Eliza => 78
    Daisy => 72
    Cindy => 100
    Becky => 85
    Alice => 95
    

[Next Chapter ↓]ArrayListの基礎
[Previous Chapter ↑]配列のコピー

超初心者のプログラム入門(C# Frame Work)