C#のLINQで最小値の要素を取り出す方法をいくつか調べてみました。
Aggregateを使う場合
using System;
using System.Collections.Generic;
using System.Linq;
public class Example1
{
struct Example
{
public string name;
public int value;
}
static public void Main ()
{
List list = new List<Example> {
new Example { name = "aaa", value = 321 },
new Example { name = "bbb", value = 432 },
new Example { name = "ccc", value = 123 }
};
Example e = list.Aggregate((a, b) => a.value < b.value ? a : b);
Console.WriteLine("{0}: {1}", e.name, e.value);
}
}
実行結果
ccc: 123
OrderByとFirstを使う場合
using System;
using System.Collections.Generic;
using System.Linq;
public class Example2
{
struct Example
{
public string name;
public int value;
}
static public void Main ()
{
List list = new List<Example> {
new Example { name = "aaa", value = 321 },
new Example { name = "bbb", value = 432 },
new Example { name = "ccc", value = 123 }
};
Example e = list.OrderBy(e => e.value).First();
Console.WriteLine("{0}: {1}", e.name, e.value);
}
}
実行結果
ccc: 123
リンク
Enumerable.Aggregate Method (System.Linq) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=netframework-4.7.2