ヤマカサのプログラミング勉強日記

プログラミングに関する日記とどうでもよい雑記からなるブログです。

実践で役立つ C#プログラミングのイディオム/定石&パターン その3

Chapter 2 C# でプログラムを書いてみよう

前回に引き続き、2章をやっていきます。

売上集計プログラム

csv ファイル
東京,リンゴ,1200
東京,オレンジ,700
東京,グレープ,870
神奈川,リンゴ,900
神奈川,オレンジ,500
神奈川,グレープ,560
埼玉,リンゴ,490
埼玉,オレンジ,770
埼玉,グレープ,680
Sale クラス

都道府県、商品カテゴリ、売上高を表す Sale クラスを定義します。

    public class Sale
    {
        // 都道府県
        public string Prefectures { get; set; }

        // 商品カテゴリ
        public string ProductCategory { get; set; }

        // 売上高
        public int Amount { get; set; }

        // 売上データを読み込み、Saleオブジェクトリストを返す
        static List<Sale> ReadSales(string filePath)
        {
            List<Sale> sales = new List<Sale>();
            // 全ての行を読み込み、配列に格納する
            string[] lines = File.ReadAllLines(filePath);
            foreach (string line in lines)
            {
                string[] items = line.Split(',');
                Sale sale = new Sale
                {
                    Prefectures = items[0],
                    ProductCategory = items[1],
                    Amount = int.Parse(items[2])
                };
            }
            return sales;
        }
    }
都道府県別の売り上げを求める

ディクショナリを用いて都道府県別の売り上げをカウントします。

    public class SalesCounter
    {
        private List<Sale> _sales;

        public SalesCounter(List<Sale> sales)
        {
            _sales = sales;
        }

        // 都道府県別売り上げを求める
        public Dictionary<string, int> GetPerPrefecturesSalse()
        {
            Dictionary<string, int> dict = new Dictionary<string, int>();
            foreach (Sale sale in _sales)
            {
                if (dict.ContainsKey(sale.Prefectures)) dict[sale.Prefectures] += sale.Amount;
                else dict[sale.Prefectures] += sale.Amount;
            }
            return dict;
        }
    }
出力
    class Program
    {
        static void Main(string[] args)
        {
            SalesCounter sales = new SalesCounter(Sale.ReadSales("sales.csv"));
            Dictionary<string, int> amountPerPrefectures = sales.GetPerPrefecturesSalse();
            foreach (KeyValuePair<string, int> obj in amountPerPrefectures)
            {
                Console.WriteLine("{0}, {1}", obj.Key, obj.Value);
            }
        }
    }

感想

csvファイルは、Debugフォルダに入れる必要がありました。パスを適切に設定しないとダメということですね。