什么是lambda就不说了 首先创建一个实体对象并赋值 public class Person { public int PId { get; set; } //自增ID public string Name { get; set; } public int Age { get; set; } } List<Person> pA = new List<Person>(); pA.Add(new Person() { PId = 1, Name = "张三", Age = 16, JobId = 1 }); pA.Add(new Person() { PId = 2, Name = "小红", Age = 18, JobId = 2 }); pA.Add(new Person() { PId = 3, Name = "王武", Age = 20, JobId = 3 }); pA.Add(new Person() { PId = 4, Name = "小梅", Age = 17, JobId = 4 }); pA.Add(new Person() { PId = 5, Name = "小李", Age = 24, JobId = 3 }); public class Job { public int JobId { get; set; } //自增ID public string JobName { get; set; } public int WorkAge { get; set; } } List<Job> jB = new List<Job>(); jB.Add(new Job() { JobId = 1, JobName = "制造业", WorkAge = 3 }); jB.Add(new Job() { JobId = 2, JobName = "IT行业", WorkAge = 5 }); jB.Add(new Job() { JobId = 3, JobName = "建筑业", WorkAge = 2 }); jB.Add(new Job() { JobId = 4, JobName = "金融业", WorkAge = 1 }); var result=PA.select(p=>p).toList(); //查询所有人(select查询) var result1=PA.Where(p=>p.Age>18).ToList(); //年龄大于18的person集合(where条件) Person per = PA.SingleOrDefault(p => p.Age == 1); //Age=1的单个people类 var netCheck = netSurveysList.FirstOrDefault(p => p.Id == netConfig.Id); //返回序列中满足条件的第一个元素Person类 var result2=PA.Where(p=>p.Age>1 && p.JobId==3).ToList(); //条件 且 var result1=PA.Where(p=>p.Age>18 && p.JobId==3).ToList(); var persons = persons.Where(p => p.Name.Contains("儿子")).ToList(); //所有Name包含儿子的Person的集合 var persons = persons.Where(r => r.Name.StartsWith("s")).ToList(); //名字以s开始,t结束 var persons = persons.Where(r => r.Name.EndsWith("t")).ToList(); var num= persons.Max(r=>r.PId); //最大值 var num= persons.Min(r=>r.PId); //最小值 var num= persons.Average(r => r.PId); //平均值 var num= persons.Sum(r => r.PId); //求和 int[] array1={1,2,3}; int [] array2={2,4,6} var quey1=array1.union(array2) //并集 1,2,3,4,6 var quey2=array1.Intersect(array2) //交集 2
var num= persons.OrderBy(r => r.PId).ToList(); //顺序 var num= persons.OrderByDescending(r => r.PId).ToList(); //倒序
var result4 = pA.Where(k => k.Age > 10).GroupBy(j => j.JobId).Select(l => l.Key).ToList(); //单个字段 var result5 = pA.Where(k => k.Age > 10) .GroupBy(a => new Person{ PId=a.PId , Name=a.Name, Age=a.Age, JobId=a.JobId }) //多个字段 .Select(a => a.Key).ToList();
var employee = empList.Select(item => new Student //将序列中的每个元素投影到新表单。返回List<Student>
{
ID = item.ID,
FName = item.FName,
Age = item.Age,
Sex = item.Sex,
}).ToList()
var result13 = pA.Select(k => k.JobId).Distinct(); //单列去重 var result9 = pA.Where(k => k.Age > 10).Count(); //count() (总行数) var result10 = pA.Average(k => k.Age); //avg() (平均年龄) var result11 = pA.Where(k => k.Name.Contains("小")).ToList(); //Contains (相当于sql中like)检索名称中有小字
注意:如果检索的是英文的话,需要大小写转换,因为linq区分大小写! var result154 = pA.Where(o => o.Age > 18).Take(3).ToList(); //获取前几条 Take (相当于top) //两个同一对象的list合并 personList.ForEach(a => personList2.Add(new person() { PId = a.pId, Name= a.Name, Age= a.Age}));