LoginSignup
2
2

More than 5 years have passed since last update.

forやforeachを使わずにList<List<T>>をList<T>にする

Last updated at Posted at 2018-03-16

List<List<T>>List<T>にする(Listを平坦化する)必要があったので、LINQを使って一発で
変換できないか調べたところ、いい方法がありました。

Program.cs
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication
{
    public class Human
    {
        public string Name { get; set; }
        public List<int> Numbers { get; set;}

        public Human(string name, List<int> results)
        {
            Name = name;
            Numbers = results;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Human> Humans = new List<Human>()
            {
                // 適当なインスタンスを作成
                new Human("Yamada", new List<int>(){ 150, 40, 180, 110, 20 }),
                new Human("Sato", new List<int>(){ 120, 80, 140, 130, 120, 180, 340 }),
                new Human("Suzuki", new List<int>(){ 10, 20, 40 })
            };

            //Humansリスト内の全ての要素のList<int> NumbersをひとつのList<int>にまとめたい
            // 冗長なコードの例1
            List<int> BadSample1 = new List<int>();
            foreach (Human human in Humans)
            {
                foreach (int num in human.Numbers)
                {
                    BadSample1.Add(num);
                }
            }

            // 冗長なコードの例2
            List<int> BadSample2 = new List<int>();
            foreach (Human human in Humans)
            {
                BadSample2.AddRange(human.Numbers);
            }

            // LINQを使った例
            // HumansのNumbersのリストの列挙を作成
            List<List<int>> AllNumbers = Humans.Select(h => h.Numbers).ToList();

            // List<List<T>>をList<T>にする(Listを平坦化する)
            List<int> AllNum = AllNumbers.SelectMany(a => a).ToList();

            // List<Human>から一発でList<int>に変換する
            List<int> allNum = Humans.SelectMany(x => x.Numbers).ToList();
        }
    }
}
2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2