2.3 LINQ

实现了​​IEnumerable<T>​​接口的类都可以使用LINQ中的方法。

数据过滤 where()

IEnumerable<Employee> list1 = list.Where(e => e.Salary > 2500 && e.Age < 35);
foreach (Employee e in list1)
{
Console.WriteLine(e);
}

获取数据条数 count()

int count1 = list.Count(e => e.Salary > 5000 || e.Age < 30);
int count2 = list.Where(e => e.Salary > 5000 || e.Age < 30).Count();

至少一条满足条件的数据Any()

//只要有符合的数据就停止
bool b1 = list.Any(e => e.Salary > 8000);
bool b2 = list.Where(e => e.Salary > 8000).Any();

获取一条数据​​Single、SingleOrDefault、First、FirstOrDefault​

方法

解释

Single

有且只有一条数据,如果没有数据或者数据大于1,则报错

SingleOrDefault

最多只有一条数据,如果没有数据,则返回类型默认值,如果多余1条,则报错

First

有一条或多条,则返回第一个,无数据则报错

FirstOrDefault

有数据,则返回第一个,否则返回了类型默认值

Employee e1 = list.Single(e => e.Id == 6);
Console.WriteLine(e1);
Employee? e2 = list.SingleOrDefault(e => e.Id == 9);
if (e2 == null)
{
Console.WriteLine("没有Id==9的数据");
}
else
{
Console.WriteLine(e2);
}
Employee e3 = list.First(e => e.Age > 30);
Console.WriteLine(e3);
Employee? e4 = list.FirstOrDefault(e => e.Age > 30);
if (e4 == null)
{
Console.WriteLine("没有大于30岁的数据");
}
else
{
Console.WriteLine(e2);
}
Employee e5 = list.First(e => e.Salary > 9999);

排序 OrderBy

var orderedItems1 = list.OrderBy(e => e.Age);//正序
var orderedItems2 = list.OrderByDescending(e => e.Salary);//倒叙

限制结果集 Skip

var orderedItems1 = list.Skip(2).Take(3);
list.Skip(2);//跳过2条数据
list.Take(2);//获取list前2条数据

聚合函数 Max、Min、Avg、Sum、Count

int maxAge = list.Max(e => e.Age);
long minId = list.Min(e => e.Id);
int minSalary2 = list.Where(e => e.Age > 30).Min(e => e.Salary);

分组 GroupBy

返回值为​​IEnumerable<IGrouping<TKey, TSource>>​​类型TKey和分组条件表达式类型一致

IEnumerable<IGrouping<int, Employee>> items = list.GroupBy(e => e.Age);
foreach (IGrouping<int, Employee> item in items)
{
int age = item.Key;
int count = item.Count();
int maxSalary = item.Max(e => e.Salary);
double avgSalary = item.Average(e => e.Salary);
Console.WriteLine($"年龄{item.Key},人数{count},最高工资{maxSalary},平均工资{avgSalary}");
}

投影 select

IEnumerable<string> names = list.Select(e => e.Gender ? "男" : "女");//将bool转换为男女
//使用匿名属性
var items = list.Select(e => new { e.Name, e.Age, XingBie = e.Gender ? "男" : "女" });
foreach (var item in items)
{
string name = item.Name;
int age = item.Age;
string xingbie = item.XingBie;
Console.WriteLine($"名字={name},年龄={age},性别={xingbie}");
}

集合转换 ToArray、ToList

查询语法

var items2 = from e in list
where e.Salary > 3000
orderby e.Age
select new { e.Name, e.Age, Gender = e.Gender ? "男" : "女" };