C# で構造体の List を作成する
こんにちは。
仕事の自動化にやりがいと達成感を感じるガッくんです。
この記事の目次
背景・目的
C# の List は使い勝手が良いですが、型が異なる値を追加するとこが出来ないので、構造体で List を作成し、異なる型の値を扱える様にします。
動作環境
・Windows 7
・Visual Studio 2017
プログラム
ソースコード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace How_to_use_Struct_and_List
{
class Program
{
// 構造体
public struct test
{
public int id;
public int r;
public double x;
public double y;
public double z;
}
static void Main(string[] args)
{
// 構造体型用の List 作成
List<test> n = new List<test>();
// List 作成
for(int i = 0; i < 20; i++)
{
// 構造体型の変数作成
test t = new test();
// 値の代入
t.id = 20 - i;
t.r = 20 - i;
t.x = 1.2345;
t.y = 12.345;
t.z = 123.45;
// List への追加
n.Add(t);
}
// コンソール出力
Console.WriteLine(string.Format("{0,5}", "id") + "," + string.Format("{0,5}", "r") + "," + string.Format("{0,10}", "x") + "," + string.Format("{0,10}", "y") + "," + string.Format("{0,10}", "z"));
for (int i=0; i<20; i++)
{
Console.WriteLine(string.Format("{0,5}", n[i].id) + "," + string.Format("{0,5}", n[i].r) + "," + string.Format("{0,10}", n[i].x) + "," + string.Format("{0,10}", n[i].y) + "," + string.Format("{0,10}", n[i].z));
}
// 何かキーが押されるまで待つ
Console.ReadKey();
}
}
}
コメント
大規模なデータの管理が簡単にできそうですね。
ソートや検索もやってみたいです。
以上