C# 配列またはリストの最後の値を取得する

C#で、配列またはリストの最後の値を取得するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Microsoft Visual Studio Community 2019 Version 16.7.1
配列またはリストの最後の値を取得
配列またはリストの最後の値を取得するには、Linqの「Last」を使用することで可能です。
// 配列を用意
int[] num = new int[] { 1, 2, 3, 4, 5 };
// 先頭の値を取得
num.Last(); // 5
以下は、リストの先頭の値を取得して、結果を表示するだけのコードとなります。
using System;
using System.Collections.Generic;
using System.Linq;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
// Listを用意
var list = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(list.Last());
System.Console.ReadKey();
}
}
}
実行結果

以下のように、条件を設定して取得することも可能です。
using System;
using System.Collections.Generic;
using System.Linq;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
// Listを用意
var list = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(list.Last(v => v % 2 == 0));
System.Console.ReadKey();
}
}
}
実行結果

-
前の記事
Linux 前回のコマンド最後の引数以外を取得する 2021.09.18
-
次の記事
docker PostgreSQL バックアップを実行する 2021.09.19
コメントを書く