Better way to return an object by max() in LINQ
I am currently learning LINQ in C# and was wondering if there was a better
way to return an object using the Max() function in a LINQ statement.
Here is my User class:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public double MonthlyWage { get; set; }
}
and this is my table population class:
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;
}
}
Here is the Main method:
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();
}
Is there a way I can return the User where the monthly wage is the maximum
without creating the double max beforehand? Is this the best way to carry
out this type of query?
No comments:
Post a Comment