LoginSignup
11
9

More than 5 years have passed since last update.

C# > 参照型(クラス)のリストと配列の初期化と列挙

Last updated at Posted at 2015-11-21

最近、参照型(クラス)の初期化とLinqや拡張メソッドを使った列挙について勉強しています。
これはその成果。
いや~、いろいろな方のブログを拝見し、やっと書けるようになりましたよ~(笑)。
ちなみにQiitaには祝初投稿!
ForEachメソッドは、ArrayにはStaticメソッドとして実装されてるんですね。

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intList = new List<int>() { 1, 2, 3 };
            List<Employee> employees = new List<Employee>()
            {
                new Employee {Id = 1, Name = "ジョン" },
                new Employee {Id = 2, Name = "ジャック" }
            };
            Employee[] employees2 = new Employee[]
            {
                new Employee {Id = 3, Name = "ジョアンナ" },
                new Employee {Id = 4, Name = "ジュリア" }
            };

            foreach (var item in intList)
            {
                Console.WriteLine($"item={item}");
            }

            employees.ForEach(o => Console.WriteLine($"Id={o.Id}, Name={o.Name}"));

            employees2.ForEach(o => Console.WriteLine($"Id={o.Id}, Name={o.Name}"));
            // 拡張メソッドを定義しない場合はこちら
            //Array.ForEach(employees2, o => Console.WriteLine($"Id={o.Id}, Name={o.Name}"));

            Console.WriteLine("\n\nPush any key!");
            Console.ReadKey();
        }
    }
}
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    public class Employee
    {
        public int Id { set; get; }
        public string Name { set; get; }
    }
}
ArrayExtension.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    public static class ArrayExtension
    {

        public static void ForEach<T>(this T[] employees, Action<T> action)
        {
            Array.ForEach(employees, action);
        }
    }
}

実行結果

item=1
item=2
item=3
Id=1, Name=ジョン
Id=2, Name=ジャック
Id=3, Name=ジョアンナ
Id=4, Name=ジュリア

Push any key!

11
9
4

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
11
9