コレクション初期化子の利用 - new の後ろに中括弧がある記述 - C#

C#でnew の後ろに中括弧がある記述ついて紹介します。

概要

C#でnewの直後に中括弧があり、中括弧内で値がカンマ区切りで記述されるコード(コレクション初期化子)について紹介します。
記述例
StrList = new List<string>() { "Cookie", "Cake", "Candy"};
補足
中括弧内で(プロパティ名)=(値)がカンマ区切りで記述される、オブジェクト初期化子についてはこちらの記事を参照してください。

コレクションの初期化子

new 演算子により、コレクションのオブジェクトのインスタンスを作成した直後にコレクションに値を設定することができます。
子の書式を利用することでコレクションへの具体的には下記のプログラムとなります。

書式

new コレクションのクラス名(){ 値1, 値2, .... 値n};
コンストラクタの括弧は省略できるため下記の書式も利用可能です。
new コレクションのクラス名{ 値1, 値2, .... 値n};

genericsに対応しているクラスの場合

genericsに対応しているクラスの場合は下記の書式になります。
new コレクションのクラス名<型名>(){ 値1, 値2, .... 値n};
コンストラクタの括弧は省略できるため下記の書式も利用可能です。
new コレクションのクラス名<型名>{ 値1, 値2, .... 値n};

プログラム例 (List コレクションの例)

UI

下図のUIを作成します。フォームにボタンを2つ、複数行のテキストボックスを1つ配置します。

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CollectionInitializer
{
  public partial class FormSimpleCollectionInitializer : Form
  {

    List<int> IntList;

    public FormSimpleCollectionInitializer()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      IntList = new List<int>() { 4, 2, 6, 10, 8, 3, 7, 12};
    }

    private void button2_Click(object sender, EventArgs e)
    {
      for (int i = 0; i < IntList.Count; i++) {
        textBox1.Text = IntList[i].ToString() +"\r\n";
      }
    }
  }
}

解説

下記コードがListクラスのインスタンスを作成し、リストのコレクションに値を設定するコードです。new 演算子の後ろの { ... } のブロックがコレクションに初期値を設定するコードです。
  IntList = new List<int>() { 4, 2, 6, 10, 8, 3, 7, 12};

上記のコードではListクラスのオブジェクトIntList に以下の値が設定されます。
インデックス
04
12
26
310
48
53
67
712


button2 のクリックイベントでは下記のコードが実行されます。こちらは、forループでIntListの要素を一つずつ取得し、テキストボックスに表示します。
  for (int i = 0; i < IntList.Count; i++) {
    textBox1.Text = IntList[i].ToString() +"\r\n";
  }

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button1]をクリックした後、[button2]をクリックします。IntListオブジェクトに設定された値がテキストボックスに表示されます。

プログラム例 (クラスのListの例)

UI

Widnows Formアプリケーションを作成し、下図のUIを作成します。

コード

下記のコードを記述します。
Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CollectionInitializer
{
  public class Product
  {
    public string Code;
    public string Name;
    public int price;
    public double weight;
  }
}
FormClassCollectionInitializer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CollectionInitializer
{
  public partial class FormClassCollectionInitializer : Form
  {

    List<Product> ProductList;

    public FormClassCollectionInitializer()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      ProductList = new List<Product>()
      {
        new Product(){Code="PG-001", Name="ぺんぎんナット", price=120, weight=2.54},
        new Product(){Code="WX-400", Name="あひるネジ", price=80, weight=1.85},
        new Product(){Code="XD-205", Name="らくだワッシャー", price=40, weight=0.36}
      };
    }

    private void button2_Click(object sender, EventArgs e)
    {
      foreach (Product p in ProductList) {
        textBox1.Text += string.Format("{0} {1} / {2:d}\r\n", p.Code, p.Name, p.price);
      }
    }
  }
}

解説

[button1]のクリックにより実行される下記のコードで、クラスのリストをコレクション初期化子を利用して初期値を設定しています。クラスオブジェクトのリストのため、値の部分にはクラスのインスタンスオブジェクト(newしたクラスのオブジェクト)を与えます。今回のコードではクラスのオブジェクトの初期値を設定にオブジェクト初期化子を利用しています。
  ProductList = new List<Product>()
  {
    new Product(){Code="PG-001", Name="ぺんぎんナット", price=120, weight=2.54},
    new Product(){Code="WX-400", Name="あひるネジ", price=80, weight=1.85},
    new Product(){Code="XD-205", Name="らくだワッシャー", price=40, weight=0.36}
  };

[button2]のクリックではforeachループによりProductList内のすべてのProductオブジェクトの要素を取得して、テキストボックスにProductオブジェクトのメンバ変数の値を表示します。
  foreach (Product p in ProductList) {
    textBox1.Text += string.Format("{0} {1} / {2:d}\r\n", p.Code, p.Name, p.price);
  }

実行結果

上記のプロジェクトを実行します。下図のウィンドウが表示されます。


[button1]クリック後[button2]をクリックします。ProductListに設定された各Productオブジェクトの値がテキストボックスに表示されます。

プログラム例 (Dictionaryの例)

Dictionaryクラスのように、インデックス作成を伴う場合の記述方法を紹介します。

書式

インデックス作成を伴う場合は以下の書式となります。
new コレクションのクラス名(){ [添字1]=値1, [添字2]=値2, .... [添字n]=値n };
コンストラクタの括弧は省略できるため下記の書式も利用可能です。
new コレクションのクラス名{ [添字1]=値1, [添字2]=値2, .... [添字n]=値n };

UI

Windows Formアプリケーションを作成し、下図のUIを作成します。

コード

下記のコードを作成します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CollectionInitializer
{
  public partial class FormDictionaryCollectionIlitializer : Form
  {

    Dictionary<string, string> mydic;

    public FormDictionaryCollectionIlitializer()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      mydic = new Dictionary<string, string>()
      {
        ["penguin"] = "のほほんペンギン",
        ["duck"] = "せかせかアヒル",
        ["camel"] = "のろのろラクダ",
        ["whale"] = "ねむねむクジラ",
        ["bear"] = "おらおらシロクマ"
      };
    }

    private void button2_Click(object sender, EventArgs e)
    {
      textBox1.Text += mydic["bear"] +"\r\n";
      textBox1.Text += mydic["penguin"] + "\r\n";
      textBox1.Text += mydic["whale"] + "\r\n";
    }
  }
}

解説

下記コードがDictionaryクラスのインスタンスを作成し、コレクション初期化子作成したインスタンスに初期値を設定するコードです。
  mydic = new Dictionary<string, string>()
  {
    ["penguin"] = "のほほんペンギン",
    ["duck"] = "せかせかアヒル",
    ["camel"] = "のろのろラクダ",
    ["whale"] = "ねむねむクジラ",
    ["bear"] = "おらおらシロクマ"
  };

上記のコードで以下の値が設定されます。
[mydic オブジェクト
キー
penguinのほほんペンギン
duckせかせかアヒル
camelのろのろラクダ
whaleねむねむクジラ
bearおらおらシロクマ


[button2]のクリックイベントのコードは下記になります。Dictionaryオブジェクトからキー名を指定して値を取得してテキストボックスに表示するコードになります。
  textBox1.Text += mydic["bear"] +"\r\n";
  textBox1.Text += mydic["penguin"] + "\r\n";
  textBox1.Text += mydic["whale"] + "\r\n";

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button1]をクリック後[button2]をクリックします。mydicオブジェクトに格納した、"bear", "penguin", "whale" のキーに対応する値がテキストボックスに表示されます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2018-05-17
iPentec all rights reserverd.