c#中的linq二
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinqInfo { public class Stu { public int ID { set; get; } public string Name { get; set; } public string Tel { get; set; } public string Address { get; set; } } public class GradeInfo { public int StuID {get;set; } public string Course{get;set;} public int grade{get;set;} } class Program { static void Main(string[] args) { List<Stu> list = new List<Stu>() { new Stu{ID=1,Name="jack1",Tel="110",Address="ChengDu"}, new Stu{ID=2,Name="jack2",Tel="112",Address="ChengDu"}, new Stu{ID=3,Name="jack3",Tel="113",Address="ChengDu"}, new Stu{ID=4,Name="jack4",Tel="114",Address="ChengDu"}, new Stu{ID=5,Name="jack5",Tel="115",Address="ChengDu"} }; //where 关键字 var query = from li in list where li.Name == "jack1" select li; //order by关键字的 //ascending 升序 //descending 降序 var query1 = from s in list orderby s.ID ascending select s; //group by的使用 var query2 = from s in list group s by s.Address into g select g; //group by 求最大值 var max = from s in list group s by s.Address into g select new { g.Key, //分组字段 MaxId=g.Max(p=>p.ID) //最大的ID }; //group by 求最小值 var min = from s in list group s by s.Address into g select new { g.Key, MidId=g.Min(p=>p.ID) }; //group by 平均值 var avg = from s in list group s by s.Address into g select new { g.Key, avgInfo = g.Average(p => p.ID) }; //group by 求和 var sum = from s in list group s by s.Address into g select new { g.Key, Sum=g.Sum(p=>p.ID) }; //这些就是group by 的基本使用滴呀; //接下来就是各种连接滴呀; List<GradeInfo> gradeList = new List<GradeInfo>() { new GradeInfo(){StuID=1,Course="语文",grade=100}, new GradeInfo(){StuID=1,Course="英语",grade=99}, new GradeInfo(){StuID=1,Course="数学",grade=88}, new GradeInfo(){StuID=2,Course="语文",grade=66}, new GradeInfo(){StuID=2,Course="英语",grade=90}, new GradeInfo(){StuID=2,Course="数学",grade=67}, //模拟错误数据 new GradeInfo(){StuID=110,Course="wrong",grade=120} }; //然后再来我们的各种连接查询滴呀; var innerJoin = from s in list join g in gradeList on s.ID equals g.StuID select new { Name=s.Name, Grade=g.grade }; //左连接; var leftJoin = from s in list join g in gradeList on s.ID equals g.StuID into joinData from g in joinData.DefaultIfEmpty() select new { Name=s.Name, Grade= g!=null ? g.grade:0 //返回相同的数据类型; }; //整体来说,再数据赛选上的效果是挺不错滴呀; //右连接; 其实左连接 和右 连接是一个相对的概念; var rightJoin = from g in gradeList join s in list on g.StuID equals s.ID into joinData from s in joinData.DefaultIfEmpty() select new { Grade=g.grade, Name=s!=null?s.Name:"" }; var result = rightJoin; //最后在附带一中linq分页的方法; var val = (from u in list orderby u.ID ascending select u).Skip(2).Take(2); //每页两条,第二页 /* * * var q=query.take(n) 这样只能取出前条n记录, * 但是还是让我们看到了分页的曙光,还是还有个skip吗, * skip可以取出除去满足条件的剩下的记录。 * 如果我们要把数据以每页pagesize的数量来进行分页, * 很简单,很skip(pagersize*pagenum)然后在剩下的记录中take(pagesize)不就得到了想要的数据了么。 * * */ var xx = val; Console.WriteLine("over"); Console.ReadLine(); } } }