C# 配列またはリストの最大値を取得する
C#で、配列またはリストの最大値を取得するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Microsoft Visual Studio Community 2019 Version 16.7.1
最大値を取得
最大値を取得するには、Linqの「Max」を使用することで可能です。
// 配列を用意
int[] num = new int[] { 1, 2, 3, 4, 5 };
// 最大値を取得
num.Max(); // 5
以下は、配列とリストの最大値を取得して、結果を表示するだけのコードとなります。
using System;
using System.Collections.Generic;
using System.Linq;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 1, 2};
int?[] arr2 = new int?[] { 0, 1, 2, 3, 4, 5, null, 2 };
List<int> list = new List<int> { 0, 1, 2, 1, 2 };
try
{
int reault1 = arr.Max();
int? reault2 = arr2.Max();
int reault3 = list.Max();
Console.WriteLine($"実行結果は{reault1}です"); // 5
Console.WriteLine($"実行結果は{reault2}です"); // 5
Console.WriteLine($"実行結果は{reault3}です"); // 2
}
catch (Exception e)
{
System.Console.WriteLine(e.ToString());
}
}
}
}
実行結果
-
前の記事
javascript lodashを使ってundefinedを生成する 2022.03.04
-
次の記事
sqlite default値が反映されない 2022.03.04
コメントを書く