明日こそ早起きする

興味あるものはなんでも

LinqのSelectManyを使って、ListでCountを持っているObjectの型をListにしてCount分増やす

なにを言っているかわからないと思うが、俺もわからない
下のコード見てどうにか理解してほしい

using System;
using System.Linq;
using System.Collection.Generic;

class Hoge{
    class Item{
        public string name;
        public int count;
    }

    static void Main(){
        List<Item> items = new List<Item>{
            new Item(){name = "水", count = 1},
            new Item(){name = "剣", count = 3},
            new Item(){name = "肉", count = 4}
        };
    }
}

Itemというクラスは名前と数をもっている
itemsというリストにはどこの誰かの持ち物が入っている

このitemsから名前だけをListにしたい
ただし、複数個(count > 1)持っている場合にはその数分Listに詰めたい
という状況

Linqを使わないで書くとこんな感じ

using System;
using System.Linq;
using System.Collection.Generic;

class Hoge{
    class Item{
        public string name;
        public int count;
    }

    static void Main(){
        List<Item> items = new List<Item>{
            new Item(){name = "水", count = 1},
            new Item(){name = "剣", count = 3},
            new Item(){name = "肉", count = 4}
        };

        List<string> itemsName = new List<string>();
        foreach(var item in items){
            for(int i = 0; i < item.count; i++){
                itemsName.Add(item.name);
            }
        }

        itemsName.ForEach(x => Console.WriteLine(x));
    }
}

結果で

水
剣
剣
剣
肉
肉
肉
肉

と出るはず。 これをLinqでやろうとすると多分一番簡単なのがこれ

using System;
using System.Linq;
using System.Collection.Generic;

class Hoge{
    class Item{
        public string name;
        public int count;
    }

    static void Main(){
        List<Item> items = new List<Item>{
            new Item(){name = "水", count = 1},
            new Item(){name = "剣", count = 3},
            new Item(){name = "肉", count = 4}
        };

        List<string> itemsName = items.SelectMany(x => Enumerable.Repeat(x.name, x.count)).ToList();

        itemsName.ForEach(x => Console.WriteLine(x));
    }
}

めっちゃ簡単
SelectManyとか初めて知った