C# の構造体で作成した List をソートする
こんにちは。
仕事の自動化にやりがいと達成感を感じるガッくんです。
この記事の目次
背景・目的
構造体で作成した List は多次元的ではありません。
しかし、 List に入っているのが、構造体の時は単なる Sort メソッドではソート出来なかったので、調べてみます。
動作環境
・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_Sort
{
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) * i;
t.x = 1.2345;
t.y = 12.345;
t.z = 123.45;
// List への追加
n.Add(t);
}
// コンソール出力
Console.WriteLine(" ソート前");
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));
}
// ソート
n.Sort((a, b) => a.id - b.id); // r でソートしたい時はこの行をコマンドアウトする
//n.Sort((a, b) => a.r - b.r); // id でソートしたい時はこの行をコマンドアウトする
// コンソール出力
Console.WriteLine("");
Console.WriteLine(" ソート後");
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();
}
}
}
コメント
r によるソートでは、同じ値がありましたが、元々のソート前の List で Index が小さい要素がソート後の List でも Index が小さい順番に並んでいました。
この事は覚えておく必要がありそうですね。
以上