我目前正在学习 C# 中的 LINQ,并且想知道是否有更好的方法来使用Max()
LINQ 语句中的函数返回对象。
这是我的用户类:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public double MonthlyWage { get; set; }
}
这是我的表人口类:
public class UsersTable
{
public IList<User> Populate()
{
IList<User> Users = new List<User>()
{
new User{ID = 1, Name = "Bob", MonthlyWage = 1200.00},
new User{ID = 2, Name = "Lee", MonthlyWage = 2200.00},
new User{ID = 3, Name = "Dan", MonthlyWage = 3200.00},
new User{ID = 4, Name = "Liam", MonthlyWage = 4200.00},
new User{ID = 5, Name = "Danny", MonthlyWage = 4213.00},
new User{ID = 6, Name = "Jonathan", MonthlyWage = 1222.00},
new User{ID = 7, Name = "Martin", MonthlyWage = 1233.00},
new User{ID = 8, Name = "Dec", MonthlyWage = 9999.99}
};
return Users;
}
}
这是主要方法:
class Program
{
static void Main(string[] args)
{
UsersTable UserTable = new UsersTable();
IList<User> Users = UserTable.Populate();
double max = Users.Max(x => x.MonthlyWage);
var maxMonthlyWage = Users
.Where(m => m.MonthlyWage == max)
.Select(x => x);
foreach (var item in maxMonthlyWage)
{
Console.WriteLine("{0}: {1} {2} MAX", item.ID, item.Name, item.MonthlyWage);
}
Console.ReadLine();
}
double max
有没有一种方法可以在不预先创建每月工资最高的情况下返回用户?这是执行此类查询的最佳方式吗?