配列、Listオブジェクト

■ 配列、List 及びArrayList の違い

    要素数の削除      要素のデータ型      メモリ確保の方法  
   配列    NG  1種類  静的
 List  OK  1種類  動的
   ArrayList    Ok  複数種類  動的



■ 配列の初期化

  

          

   
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 WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        Encoding encSjis = Encoding.GetEncoding("shift-jis");
        Encoding encUni = Encoding.GetEncoding("unicode");
        public Form1()
        {
            InitializeComponent();


         //宣言
            int[] Num = new int[32];
            char[] str = new char[32];
            string[] myStr0 = new string[32];
            byte[] array1 = new byte[64];

        //定義
            int[] numbers = new int[3] { 4, 5, 6 };

            string Japan = "japan";
            string America = "america";
            string UK = "u.k.";
            string France = "france";
            string[] myStr1 = new string[4] {Japan, America, UK, France};

            string input = textBox1.Text;
            byte[] array2 = new byte[input.Length];
            byte[] byteUni = Encoding.Convert(encSjis, encUni, array2);

        }
    }
}






■ 文字列を行単位で 配列に変換する

   文字列をStringクラスのSplitメソッドで \n により分割する。 分割後の要素に \nは含まれない
 
   <プログラム例>

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 WindowsFormsApp1 { public partial class Form1 : Form { string[] array1; //string文字列の配列を定義 string str0 = "只今\nマイクの\n試験中\n本日は\n晴天なり"; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { array1 = str0.Split('\n'); //\nで分割、\nは削除される for (int i = 0; i < array1.Length; i++) array1[i] = array1[i] + "\n"; //全要素の最後に \n (LF改行)追加 foreach (string str in array1) { richTextBox1.AppendText(str); } } } }
 
  実行結果
 



 配列の要素を変更する

    変更を加えたい要素に直接上書きします。
 

         

   <プログラム例>

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 richText1_to_2_by_List
{
    public partial class Form1 : Form
    {
        string[] array1;     //string文字列の配列を定義
        public Form1()
        {
            InitializeComponent();

            string str0 = "只今\nマイクの\n試験中\n本日は\n晴天なり";
            
            richTextBox1.Text = str0;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            array1 = (richTextBox1.Text).Split('\n');   //'\n'で文字列を分割 → 文字列の配列に変換

            //配列の一部を上書きで、書き換え
            array1[0] = "ただいま";
            array1[2] = "しけんちゅう";

            //要素に行番号追加
            for (int i = 0; i < array1.Length; i ++) array1[i] = (i + 1).ToString() + ". " + array1[i] + "\n";

            foreach (string str1 in array1)    //リッチテキストボックス
            {
                richTextBox2.AppendText(str1);   //1アイテム毎に追加
            }
        }
    }
}
  実行結果
   button1 クリック前  button1 クリック後
 



■ 配列を1つの文字列に結合する。 配列に要素を追加する


    ・SringクラスのJoinメソッドで配列の全要素を結合して、1つの文字列にします。
・ArrayクラスのResizeメソッドで配列の要素を増やした後、追加した要素を定義します。
 

          

   <プログラム例>

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 WindowsFormsApp1 { public partial class Form1 : Form { string[] array1 = { "Tokyo", "Sendai", "Nagoya", "Osaka" }; //省略形定義 // string[] array1 = new string[4] { "Tokyo", "Sendai", "Nagoya", "Osaka" };  …… FULL定義 // string[] array1 = new string[] { "Tokyo", "Sendai", "Nagoya", "Osaka" }; ……一部省略定義 public Form1() { InitializeComponent(); richTextBox1.Text = String.Join("\n",array1); //\n で接続して、文字列に変換 //文字列の結合 } private void button1_Click(object sender, EventArgs e) { Array.Resize(ref array1, array1.Length + 2); //サイズを2つ増加 ここでのarray1.Length= 4 array1[array1.Length - 2] = "Hiroshima"; //最後尾の前の要素 //ここでのarray1.Length= 6 array1[array1.Length - 1] = "Kumamoto"; //最後尾の要素 //ここでのarray1.Length= 6 richTextBox2.Text = String.Join("\n", array1); //\n で接続して、文字列に変換 //文字列の結合 } } }
  実行結果
  button1クリック前 button1クリック後
 





■ 配列の要素を削除する

   直接配列の要素は削除できません。以下の手順を踏む必要があります。
1. 配列をListオブジェクトに変換する。
2. Listオブジェクトのリストから所要のリストを削除する
3. Listオブジェクトを配列変換する。
 

          

   <プログラム例>
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 Remove_Array_Element
{
    public partial class Form1 : Form
    {

        string[] array1 = { "1. Tokyo", "2. Sendai", "3. Nagoya", "4. Osaka", "5. Hiroshima", "6. Kumamoto" };  //配列初期化、定義
        public Form1()
        {
            InitializeComponent();

            richTextBox1.Text = String.Join("\n", array1);  //配列を文字列に変換してリッチテキストボックスに表示
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var list1 = new List<string>(); //list1オブジェクトを生成
            list1.AddRange(array1);         //配列array1をlist1オブジェクトを変換

            list1.Remove("4. Osaka");   //list1オブジェクトから "4. Osaka" を削除

            list1.Remove("5. Hiroshima");   //list1オブジェクトから "5. Hiroshima" を削除

            string[] array2;

            array2 = list1.ToArray();   //list1オブジェクトを配列array2に変換

            richTextBox2.Text = String.Join("\n", array2);  //配列array2を\nで結合して、リッチテキストボックスに表示
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}
   実行結果
   button1クリック前  button1クリック後
 





■ 配列の要素を削除する(要素のインデックスを指定する場合)

   ListクラスのRemoveAtメソッドを使って要素のインデックスを指定して削除することもできます。
 

          

   <プログラム例>

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 Remove_array_by_Index { public partial class Form1 : Form { string[] array1 = { "Tokyo", "Sendai", "Nagoya", "Osaka", "Hiroshima", "Kumamoto" }; //配列定義 public Form1() { InitializeComponent(); richTextBox1.Text = String.Join("\n", array1); //Joinメソッドで文字列化 } private void button1_Click(object sender, EventArgs e) { // List<string> list1 = new List<string>(array1); var list1 = new List<string>(array1); //こちらも可 list1.RemoveAt(3); //ListクラスのRemoveAtメソッドで list1[3]要素を削除 list1.RemoveAt(4); //ListクラスのRemoveAtメソッドで list1[3]要素を削除 array1 = list1.ToArray(); //Listオブジェクトを配列に変換 //はじめのarray1 配列の要素が2つ削減された richTextBox2.Text = String.Join("\n", array1); } } }
   実行結果
   button1クリック前  button1クリック後
 




■ 配列の要素を削除する(要素のインデックスの範囲を指定する場合)

    ListクラスのRemoveRange(int index, int length)メソッドによりインデックスの削除範囲を指定します。
 

          

   <プログラム例>

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 Remove_range_Array
{
    public partial class Form1 : Form
    {
        string[] array1 = { "Tokyo", "Sendai", "Nagoya", "Osaka", "Hiroshima", "Kumamoto" };    //配列初期化
        public Form1()
        {
            InitializeComponent();

            richTextBox1.Text = String.Join("\n", array1);  //配列結合
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> list1 = new List<string>(array1);  //Listオブジェクト生成
            // var list1 = new List<string>(array1);        //var 匿名型でもオブジェクト生成可能

            list1.RemoveRange(1, 4);    //インデックス 1 ~ 4 を削除

            array1 = list1.ToArray();   //Listオブジェクトを配列に変換

          

            richTextBox2.Text = String.Join("\n", array1);  //配列を結合して リッチテキストボックスに表示
        }
    }
}
   実行結果
  button1クリック前 button1クリック後
 



■ 指定の文字列を含む配列要素を削除する

    リストクラスのRemoveAllメソッドの引数にデリゲートを使用して削除を実行します。 このデリゲートに削除の要件を定義します。
ここでの例では、文字列 Kanto と Osaka を含む要素をリストオブジェクトから削除しています。
 

          

   <プログラム例>
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 Remove_with_Condition
{
    
    //指定の文字列を含む要素を削除
    public partial class Form1 : Form
    {
        string[] array1 = { "Tokyo_Kanto", "Chiba_Kanto", "Yokohama_Kanto","Osaka_Kansai", "Kobe_Kansai", "Kyoto_Kansai" };    //配列初期

        public Form1()
        {
            InitializeComponent();

            richTextBox1.Text = String.Join("\n", array1);

        }
        

        //削除条件を定義するデリゲート
        static bool strCheck(string str)
        {
            bool judge;

          //Kanto または Osaka を含む文字列を含む要素を リストから除外する
            if ((str.Contains("Kanto") == true) || (str.Contains("Osaka") == true)) judge = true;
            else judge = false;

            return judge;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> list1 = new List<string>(array1);  //リスト作成
            //    var list1 = new List<string>(array1);  //リスト作成

            list1.RemoveAll(strCheck); //条件にもとづくリスト作成

            richTextBox2.Text = String.Join("\n", list1);   //リストを \n で結合し テキストボックスに表示
        }
    }
}
   実行結果
  button1クリック前  button1クリック後
 


■ 指定文字列xN個以上を含む配列要素のみ残す
  (指定の文字列xN個以下を含む配列要素を削除する
)

   リストクラスのRemoveAllメソッドの引数にデリゲートを使用して削除を実行します。 このデリゲートに削除の要件を定義します。
”指定文字列xN個以上を含む配列要素のみ残す” を
”指定の文字列xN個以下を含む配列要素を削除する” に論理変更してRemoveAllメソッドをつかい実現しています。
 

          

   <プログラム例>
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 Specified_N_chara_Element_Remain
{
    public partial class Form1 : Form
    {
        string[] array1 = {"", ",", ",,", ",,,", ",,,,",
                           "a", "a,a", "a,a,a", "a,a,a,a", "a,a,a,a,a",
                           "xyz", "xyz,xyz", "xyz,xyz,xyz", "xyz,xyz,xyz,xyz", "xyz,xyz,xyz,xyz,xyz"};
        
        public Form1()
        {
            InitializeComponent();


            label3.Text = "指定文字列が \",\" x 2個以下の要素を削除の場合" +
                "\n   (\",\" x3個以上の要素を選択した場合)";

          //  label3.Text = "指定文字列が \"xyz\"x 2個以下の要素削除の場合" +
          //"\n   ( \"xyz\" x3個以上の要素を選択した場合)";


            richTextBox1.Text = String.Join("\n", array1);
        }

        //削除条件を定義するデリゲート
        static bool strCheck(string str)
        {
            bool judge;
            int startPosi = 0;
            int endPosi = 0;

            int Num = 0;

            do
            {
                endPosi = str.IndexOf(",", startPosi);          //label3.Text = "指定文字列が ","x 2個以下の要素を削除の場合"";
             //   endPosi = str.IndexOf("xyz", startPosi);    //label3.Text = "指定文字列が "xyz"x2個以下の要素を削除の場合";

                if (endPosi >= 0)
                {
                    startPosi = endPosi + 1;
                    Num++;                      //指定文字列の数をカウント
                }
            } while (endPosi >= 0);


            if (Num  <=  2)
            {
                judge = true;      // , が2個以下の要素を削除     //要素削除
            }
            else
            {
                judge = false;      //要素 非削除
            }

            return judge;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> list1 = new List<string>(array1);  //リスト作成
            //    var list1 = new List<string>(array1);  //リスト作成

            list1.RemoveAll(strCheck); //条件にもとづくリスト作成

            richTextBox2.Text = String.Join("\n", list1);   //リストを \n で結合し テキストボックスに表示

        }
    }
}
  指定文字列が "," x 2個以下の要素を削除の場合
   ("," x3個以上の要素を選択した場合)
   button1クリック前  button1クリック後
 
   指定文字列が \"xyz\"x 2個以下の要素削除の場合
  ( \"xyz\" x3個以上の要素を選択した場合)
   button1 クリック前  button1 クリック後
 




■ Listオブジェクトの初期化

   Listオブジェクトは  List<string>だけでなく 匿名型 var でも初期化できます。
  

          

   <プログラム例>
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 Initialize_List
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            List<string> list1 = new List<string>();    //

            list1.Add("Japan");     //リストに"Japan\n"を追加
            list1.Add("America");
            list1.Add("U.K.");

            richTextBox1.Text = String.Join("\n", list1);   //\nで要素を結合して1つの文字列に変換


            var list1v = new List<string>();        //var でも初期化可

            list1v.Add("Emperor");     //リストに"Japan"を追加
            list1v.Add("President");
            list1v.Add("Prime Minister");
            richTextBox2.Text = String.Join("\n", list1v);


            List<string> list2 = new List<string>() { "Tokyo", "Osaka", "Nagoya" }; //値を指定して初期化
            richTextBox3.Text = String.Join("\n", list2);


            var list2v  = new List<string>() { "Edo", "Naniwa", "Nagoya" };          //var でも初期化可
            list2v[2] = "Owari";                                                    //既存の要素変更
            richTextBox4.Text = String.Join("\n", list2v);


        }
    }
}

  実行結果
 






■ Listオブジェクトにアイテムを追加

    動的配列クラス Listにアイテムを追加後、foreachを使ってリッチてきすとボックスに表示します。
 
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 Add_List_to_richtext
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

var strList = new List<string>(); //匿名型動的配列クラス List

//List
strList.Add("Japan\n"); //リストに"Japan\n"を追加
strList.Add("America\n");
strList.Add("U.K.\n");
strList.Add("France\n");
strList.Add("German\n");


foreach (var str in strList) //リッチテキストボックス
{
richTextBox1.AppendText(str); //1アイテム毎に追加
}


}
}
}
  実行結果
 




標準表示文字列を16進表示の文字列に変換

    通信などで標準文字列を16進数表示の文字列に変換する場合があります。 以下の手順でおこないます。
➀ 標準文字列をバイトの配列に変換します。
➁ 各配列要素を16進数に変換します。
③ 各配列要素を結合して文字列にします。、
 

     

          

   <プログラム例>
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;


//標準表示文字列を16進表示の文字列に変換

namespace To16shinStrings
{
    public partial class Form1 : Form
    {
        //文字を変換するクラスを宣言
        Encoding encSjis = Encoding.GetEncoding("shift-jis");
        Encoding encUni = Encoding.GetEncoding("unicode");
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string input;
            int i;

            char[] ys = new char[20];
            int [] num = new int[20];
            string[] myStr0 = new string[20];
            string[] myStr1 = new string[20];

            input = textBox1.Text;

            Byte[] array1 = encSjis.GetBytes(input); //'送信文字をShift-jisに変換してをByte配列に格納


            richTextBox1.Text = String.Join("\n", array1);   //\n で接続して、文字列に変換   //文字列の結合


            for (i = 0; i < array1.Length; i++)
            {
                num[i] = array1[i];
                myStr0[i] = num[i].ToString("X");  //小文字で表示
                myStr1[i] = "0x" + myStr0[i];  //小文字で表示
            }



            richTextBox2.Text = String.Join("\n", myStr1);   //\n で接続して、文字列に変換   //文字列の結合
            textBox2.Text = String.Join("", myStr0); //区切り文字なしで文字列を結合




            byte[] byteUni = Encoding.Convert(encSjis, encUni, array1);   //shift-jis からunicodeに変換する    //バイト配列変換

            textBox3.Text = encUni.GetString(byteUni);  //配列を文字列に変換

        }

      
    }
}
 
  実行結果
 


■ 16進表示文字列を標準文字列に変換

   ・ マニュアルで16進数の文字列をつくるのは大変なので ダイアログ下部で任意の16進数文字列をつくるようになっています。これをコピーして
上段の16進数文字列入力テキストボックスに貼り付けて使います。
<変換要領>
・ 16進数文字列を2個単位で配列化して、シフトJISの配列を作成しします。
・ シフトJISの配列をunicodeの配列に変換します。
・ unicodeの配列をunicodeの文字列に結合します。 
 

          

   
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 WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        //文字を変換するクラスを宣言
        Encoding encSjis = Encoding.GetEncoding("shift-jis");
        Encoding encUni = Encoding.GetEncoding("unicode");
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)  //標準文字列 → 16進数表示文字列 ボタン
        {
            string input;
            int i;
            int[] num = new int[20];
            string[] myStr0 = new string[20];

            input = textBox1.Text;
            byte[] array1 = encSjis.GetBytes(input); //'送信文字をShift-jisに変換してをByte配列に格納


            for (i = 0; i < array1.Length; i++)
            {
                num[i] = array1[i];
                myStr0[i] = num[i].ToString("X");  //16進数文字列に変換 //大文字で表示 vs "x"
            }

            textBox2.Text = String.Join("", myStr0); //区切り文字なしで文字列を結合、テキストボックスに表示
        }

        private void button2_Click(object sender, EventArgs e)      //16進数文字列 → 標準文字列  ボタン
        {
            try
            {
                int Num = 0;
                int i;

                string input = textBox3.Text;
                byte[] array2 = new byte[input.Length / 2]; //shift-JIS バイト配列

                for (i = 0; i < input.Length; i = i + 2)
                {
                    string str = input.Substring(i, 2);   //先頭からi番目から 2個づつ文字列化
                    array2[Num] = Convert.ToByte(str, 16);  // 16進数文字列x2個を 標準文字x1個に変換
                    Num++;
                }


                byte[] byteUni = Encoding.Convert(encSjis, encUni, array2);   //shift-jis からunicodeの配列に変換する

                string strUni = encUni.GetString(byteUni);  //配列を文字列に変換

                textBox4.Text = strUni; //テキストボックスに表示

            }
            catch
            {

            }


        }
    }
}

 
  実行結果