LINQ简单案例
1.在visual studio 创建一个解决方案,新建一个控制台程序Kong
2.新建两个类,分别为Master 类和Kongfu类 Master类中包含成员如下,并重写ToString方法
1 namespace linQ 2 { 3 class Master 4 { 5 public int id; 6 public string name;//什么人 7 public string kongfu;//什么功夫 8 public int level;//武学等级 9 10 public override string ToString() 11 { 12 return "序号" + id +" "+ "名字" + name +" " +"功夫" + kongfu +" " +"武学等级" + level; 13 } 14 } 15 }
Kongfu类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace linQ 8 { 9 class Kongfu 10 { 11 public int id;//武学ID 12 public string name;//武学名称 13 public int power;//伤害 14 15 public override string ToString() 16 { 17 return "ID为" + id + "名字" + name + "伤害" + power; 18 } 19 } 20 }
Main方法中进行查询
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel.Design; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace linQ 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 //创建一个LIST列表,并插入数据 15 List<Master> master=new List<Master>() 16 { 17 new Master(){id=1,kongfu="葵花宝典",level =10,name = "东方不败"}, 18 new Master(){id=2,kongfu="独孤九剑",level = 4,name ="令狐冲"}, 19 new Master(){id=3,kongfu ="辟邪剑谱",level = 2,name="林平之"}, 20 new Master(){id=4,kongfu="葵花宝典",level =8,name="岳不群"} 21 22 }; 23 List<Kongfu> kongfu=new List<Kongfu>() 24 { 25 new Kongfu(){id=1,name ="葵花宝典",power =300}, 26 new Kongfu(){id=2,name = "独孤九剑",power = 200}, 27 new Kongfu(){id=3,name = "辟邪剑谱",power = 150} 28 29 }; 30 //LINQ方法查询数据 31 /*var res = from m in master 32 where m.level > 8//查询武学等级大于8的人的相关数据 33 select m;*/ 34 //如果查询两个表相关的数据 35 // var res = from master1 in master 36 // from kongfu1 in kongfu 37 //查询等级大于4并且上大于武学伤害大于200的相关数据 38 // where master1.level > 4 && kongfu1.power > 200 39 //select new {a=master1,b=kongfu1}; 40 //select master1.name;//只输出修炼人的名称 41 42 //如果要对结果根据等级进行排序,查询修炼葵花宝典的人,并进行等级排序 43 /*var res1 = from m in master 44 from n in kongfu 45 where m.kongfu == "葵花宝典" 46 orderby m.level 47 select m;*/ 48 //如果用Join on方法进行连接,根据两个类中的武学进行连接 49 var res2 = from m in master 50 join n in kongfu on m.kongfu equals n.name 51 where m.level > 8 52 select m.name; 53 54 55 56 //用循环遍历输出显示想要查询的结果 57 foreach (var a in res2) 58 { 59 Console.WriteLine(a); 60 } 61 Console.ReadKey(); 62 } 63 } 64 }