【发布时间】:2013-09-12 14:06:45
【问题描述】:
我目前正在学习 C# 中的 LINQ,想知道是否有更好的方法可以在 LINQ 语句中使用 Max() 函数返回对象。
这是我的用户类:
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 的情况下返回月工资最高的用户?这是执行此类查询的最佳方式吗?
【问题讨论】:
-
您不需要
.Select(x => x)- 它完全是多余的。Where方法将为您提供所需的内容。只有在需要更改返回的内容时才应使用 select:.Select(x => new SomethingElse { Something = x })。 -
谢谢@Dan 我不知道
-
从您的原始代码中,我了解到您期望不止一个 Max。价值发生(这就是我不依赖 First 的原因)。如果是这种情况,Tommy Grovnes 的方法并不能提供您想要的,因为总是只输出一次。正如 MarcinJuraszek 正确指出的那样,我的原始代码效率太低了。我已经纠正了它,现在好多了。在任何情况下,它的效率都比您原始代码中的效率差(甚至可以通过不依赖 LINQ 进一步提高)。