C# の構造体で作成した List の検索方法
こんにちは。
仕事の自動化にやりがいと達成感を感じるガッくんです。
この記事の目次
背景・目的
C# の List は使い勝手が良いです。検索も BinarySearch が使えたりします。
しかし、構造体で List を作成した時は BinarySearch が使えなかったので、 FindIndex を使用して検索してみました。
動作環境
・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_Search
{
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 < 15; 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 < 15; 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);
// コンソール出力
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 < 15; 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));
}
// r が 51 の Index 検索
var idx = n.FindIndex(a => a.r == 51);
// コンソール出力
Console.WriteLine("");
Console.WriteLine(" r = 51 の Index");
Console.WriteLine(string.Format("{0,5}", idx));
// 何かキーが押されるまで待つ
Console.ReadKey();
}
}
}
コメント
r が 51 の Index は 11 でした。
検索結果は 0(ゼロ) から始まります。
データが大容量の時の検索スピードが気になるところです。
以上