【C#】【VB.NET】Listや配列を1行のLinqクエリで列挙する

Listや配列を簡潔に列挙する手法をノートします

参考サイト
stackoverflow.com

C#の場合

class Student
{
    public int Code;
    public string Name;
    public Student(int p1, string p2)
    {
        Code = p1;
        Name = p2;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 整数配列を列挙する
        int[] array = new int[] { 1, 3, 5 };
        array.ToList().ForEach(x => Console.WriteLine(x));

        // StudentクラスListを列挙する
        List<Student> students = new List<Student>();
        students.Add(new Student(1, "Alice "));
        students.Add(new Student(2, "Bod"));
        students.ForEach(x => Console.WriteLine(x.Code + ": " + x.Name));
    }
}

VB.NETの場合

Class Stundent
    Public No As Integer
    Public Name As String
    Sub New(p1 As Integer, p2 As String)
        No = p1
        Name = p2
    End Sub
End Class

Sub Main(args As String())
    ' 整数配列を列挙する
    Dim array As Integer() = {1, 3, 5}
    array.ToList().ForEach(Sub(x) Console.WriteLine(x))

    ' StudentクラスListを列挙する
    Dim students As New List(Of Stundent)
    students.Add(New Stundent(1, "Alice"))
    students.Add(New Stundent(2, "Bob"))
    students.ForEach(Sub(x) Console.WriteLine(x.No & ": " & x.Name))

    Console.ReadKey()
End Sub

結果
f:id:ktts:20200123211415p:plain