俺氏、本を読む

30歳になるまでに本を読んで勉強しようかと。主に啓発、お金についての本を読むつもり。一応プログラマーなのでその辺のことも。あと、せどり(転売)の仕入れ見込み商品をリサーチして仕入先と一緒に投稿します

【C#.NET】List<T>の型変換

今までListの型変換ってしたことないなぁ

と思ったのでメモ的な。

 

とりあえず使うメソッドは「ConvertAll」というメソッド。

ラムダ式をつかった単純な型変換と、

Converter<TInput, TOutput> デリゲートを使ったちょっと複雑な型変換の方法

 単純な型変換

ConvertAllメソッドとラムダ式を使って、

List<string> → List<int> みたいに変換する方法

List<string> strList = new List<string>(){"1","2","3","4","5","6"};
// string → int
List<int> iList = strList.ConvertAll(x => int.Parse(x));

これだけwww

Converter<TInput, TOutput> デリゲート

これはクラスとか構造体をListのテンプレートに指定している時とかに便利・・・と思う。

例えば以下のような構造体があったとして

public struct test1
{
    public int iMax;
    public int iMin;
    public test1(int max, int min)
    {
        this.iMax = max;
        this.iMin = min;
    }
}
public struct test2
{
    public string strMax;
    public string strMin;
    public test2(string max, string min)
    {
        this.strMax = max;
        this.strMin = min;
    }
}

それをメンバ変数ごとに型変換する。みたいなイメージ。

static void Main(string[] args)  
{  
    List<test1> tstList = new List<test1>();
    tstList.Add(new test1(10, 1));
    tstList.Add(new test1(100, 10));
    tstList.Add(new test1(1000, 100));
    tstList.Add(new test1(10000, 1000));

    List<test2> tst2List = tstList.ConvertAll(new Converter<test1, test2>(test1Totest2));
}

public static test2 test1Totest2(test1 pf)
{
    return new test2(pf.iMax.ToString(), pf.iMin.ToString());
}

Converter<TInput, TOutput> デリゲートを使えば結構複雑な変換が必要でもできそうよね。

まぁそんな使う機会ないかもやけど(^_^;)

 

参考サイト:

List(T).ConvertAll(TOutput) メソッド (System.Collections.Generic)

c# Cast List<X> to List<Y> - Stack Overflow