Linq-聚合函数
1.Max 获取最大值
// 获取 Id>6的人群中的最高工资
double a = list.Where(it => it.Id > 5).Max(it => it.Salary) ;
string b = list.Max(it => it,Name);
根据Func(有返回值的委托),返回值是什么类型,前面就用什么类型的变量去接收
2.Average 获取平均值
//取年龄>30岁的平均工资
double a = list.Where(it => it.Age >= 30).Average(it => it.Salary)
3.Min 最小值
4.Sum 求和
item.Sum(it => it.Salary);
5.Count 总数
list.Count();
6.GroupBy 分组
class Program
{
static void Main(string[] args)
{
List<Employee> list = new()
{
new Employee { Id = 1, Name = "Hpf", Age = 38, Gender = true, Salary
= 1000 },
new Employee { Id = 2, Name = "Jim", Age = 15, Gender = true, Salary
= 2000 },
new Employee { Id = 3, Name = "Lily", Age = 27, Gender = false,
Salary = 1500 },
new Employee { Id = 4, Name = "Kimi", Age = 15, Gender = true,
Salary = 2700 },
new Employee { Id = 5, Name = "Nancy", Age = 38, Gender = false,
Salary = 3200 },
new Employee { Id = 6, Name = "Jack", Age = 21, Gender = false,
Salary = 4400 },
new Employee { Id = 7, Name = "Zack", Age = 38, Gender = true,
Salary = 7500 }
};
IEnumerable<IGrouping<int, Employee>> items = list.GroupBy(it =>
it.Age);
foreach (IGrouping<int, Employee> item in items)
{
Console.WriteLine(item.Key);
Console.WriteLine($"最大工资:{item.Max(it => it.Salary)}");
foreach (Employee e in item)
{
Console.WriteLine(e);
}
Console.WriteLine("*****************");
}
Console.ReadLine();
}
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool Gender { get; set; }
public double Salary { get; set; }
public override string ToString()
{
return $"Id={Id},Name={Name},Age={Age},Gender={Gender},Salary={Salary}";
}
}