1.はじめに
list配列では、整数型、文字列型の可変配列の使用例はよく見かける。
ただ、型の違うデータを纏めて扱いたいことがある。
こんな時にはカスタムクラス型のlistを作成することになる。
忘れないために、自分用のメモとして本記事を書いている。
2.カスタムクラス型のListメモ
前提
クラス名:loto6
メンバ変数:numdata,stardata
numdata:6つの数字の組み合わせ
stardata:6番目の数字分の★
list名:list_lt6
(1)カスタムクラス型(loto6)のlistを作成
List<loto6> list_lt6 = new List<loto6>();
(2)カスタムクラス型のlistにデータ追加
loto6 lt=new loto6();
lt.numdata="1,2,6,4,5,3";
lt.stardata="★★★";
list_lt6.Add(lt);
loto6 lt2=new loto6();
lt2.numdata="11,2,16,34,25,6";
lt2.stardata="★★★★★★";
list_lt6.Add(lt2);
(3)カスタムクラス型のlistの要素へのアクセス
//2番目のデータのstardataを表示
Console.WriteLine(list_lt6[1].stardata)
3.ソース
処理内容:
6数字の組み合わせと、6番目の数字数の★を
5回表示するプログラム
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace con_loto6_list
{
internal class Program
{
//ランダムにType0個の数字を生成
static int[] make_lotodata(int Max,int Type0,Random rand)
{
List<int> lotoqp_list = new List<int>();
int nn;
for (int j = 1; j <= Max; j++)
{
lotoqp_list.Add(j);
}
int[] tmplist = new int[Type0];
for (int j = 0; j < Type0; j++)
{
nn = rand.Next(Max - j);
tmplist[j] = lotoqp_list[nn];
lotoqp_list.RemoveAt(nn);
}
lotoqp_list.Clear();
return tmplist;
}
//n0個の★を作成
static string printstar(int n0)
{
string retstr = "";
for (int i = 0; i < n0; i++) retstr += "★";
return retstr;
}
static void Main(string[] args)
{
int n=5;
int Max = 43;
int Type0 = 6;
List<loto6_qp> list_lt6 = new List<loto6_qp>();
int[] arr_lt = new int[6];
Random rand = new Random();
for (int i = 0; i < n; i++)
{
arr_lt = make_lotodata(Max,Type0,rand);
loto6_qp lt =new loto6_qp();
lt.Loto6_data = string.Join(",",arr_lt);
lt.Loto_star = printstar(arr_lt[5]);
list_lt6.Add(lt);
}
for(int i = 0; i < n; i++)
{
Console.WriteLine(list_lt6[i].Loto6_data + ":" + list_lt6[i].Loto_star);
}
Console.WriteLine("キーを押すと終了します");
Console.ReadKey();
}
}
}
loto6_qp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace con_loto6_list
{
internal class loto6_qp
{
private string _loto6_data;
private string _loto_star;
public string Loto6_data
{
set { _loto6_data = value; }
get { return _loto6_data; }
}
public string Loto_star
{
set { _loto_star = value; }
get { return _loto_star; }
}
}
}
4.実行結果
31,26,22,41,24,13:★★★★★★★★★★★★★
18,24,17,35,31,4:★★★★
37,34,27,14,9,15:★★★★★★★★★★★★★★★
19,22,13,20,36,7:★★★★★★★
10,20,33,27,2,36:★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
キーを押すと終了します
5.気づいたこと
データサイズが可変の構造体のようなものなのかもしれない。