Linq-常用的方法
往集合中填充一些基础数据
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 }
};
Console.ReadLine();
}
}
}
1.Count() 获取数据条数
list.Count(it => it.Age > 18 && it.Salary > 5000);
2.Any() 是否至少有一条数据
bool B = list.Any(it => it.Salary > 8000)
3.Single 有且只有一条满足要求的数据
多条满足条件或一条也没有,此方法会报错
Employee e = list.Single(it => it.Name=="Hpf");
Console.WriteLine(e == null);
4.SingleOrDefault 最多有一条满足要求的数据
多条满足条件,此方法会报错;没有数据则返回数据类型的默认值
int[] nums = new int[] {3,4,8};
int i = nums.SingleOrDefault(it => it>10);
Console.WriteLine(i);
-- OutPut 0
5.First 至少有一条,返回第一条
一条也没有,此方法会报错
6.FirstOrDefault 返回第一条或默认值
7.OrderBy() 对数据正序排序
list.OrderBy(it => it.Age>18);
8.OrderByDescending() 倒序排序
list.OrderByDescending(it => it.Age>18);
9.ThenBy()、ThenByDescending() 多规则排序
list.OrderBy(it => it.Age>18).ThenBy(it => it.Salary);
10.Skip(n)、Take(n) 限制结果集,获取部分数据
-- 从第二条数据开始,获取三条数据
list.Skip(2).Take(3);