请写一个共用方法,获取不同List<TEntity>的指定字段的最大值
时间: 2024-04-29 17:23:29 浏览: 140
以下是一个获取指定字段最大值的共用方法:
public static T GetMaxValue<T, TEntity>(List<TEntity> entities, Func<TEntity, T> selector)
{
T maxValue = default(T);
bool first = true;
foreach (TEntity entity in entities)
{
T value = selector(entity);
if (first || Comparer<T>.Default.Compare(value, maxValue) > 0)
{
maxValue = value;
first = false;
}
}
return maxValue;
}
使用示例:
// 假设有一个Student类,有两个属性:Name和Score
List<Student> students = new List<Student>
{
new Student { Name = "小明", Score = 90 },
new Student { Name = "小红", Score = 80 },
new Student { Name = "小刚", Score = 95 }
};
// 获取Score字段的最大值
int maxScore = GetMaxValue(students, s => s.Score);
Console.WriteLine(maxScore); // 输出:95
// 获取Name字段的最大值
string maxName = GetMaxValue(students, s => s.Name);
Console.WriteLine(maxName); // 输出:"小红"
相关推荐


















