namespace LinQ数据查询
{
class Kongfu
{
public int Id { get; set; }
public string Name { get; set; }
public int Power { get; set; }
}
}
______________________________________
namespace LinQ数据查询
{
class MartiaArtsMaster
{
public int Id { get; set; }
public string Name { get;set;}
public int age { get; set; }
public string Menpai { get; set; }
public string KongFu { get; set; }
public int Level { get; set; }
}
}
先创建两个类
————————————————————————————————————
namespace LinQ数据查询
{
class Program
{
static void Main(string[] args)
{
var masterList = new List<MartiaArtsMaster>()
{
new MartiaArtsMaster(){Id =1,Name ="黄蓉",age =18,Menpai ="丐帮",KongFu="打狗棍法",Level=9},
new MartiaArtsMaster(){Id =2,Name ="任我行",age =70,Menpai ="明教",KongFu="葵花宝典",Level=10},
new MartiaArtsMaster(){Id =3,Name ="风清扬",age =23,Menpai ="华山",KongFu="独孤九剑",Level=2},
};
var kongfuList = new List<Kongfu>()
{
new Kongfu () {Id=1,Name="打狗棒法",Power=90},
new Kongfu () {Id=2,Name="葵花宝典",Power=100 },
new Kongfu () {Id=3,Name="独孤九剑",Power=100},
};
//var res =new List<MartiaArtsMaster>(); //先不使用LINQ ,建一个列表用来存储结果
//foreach (var temp in masterList) //var 一个临时变量 查询等级大于8的 武林高手
//{
// if (temp.Level > 8)
// {
// res.Add(temp); //在加入到res列表中
// }
//}
// var res = masterList.Where(m => m.Level > 8).OrderBy(m => m.Level).ThenBy(m => m.age);
//双排列 先OrderBy 然后ThenBy 排序
//var res = from m in masterList //form后面设置查询的集合,m是集合中的元素
// where m.Level > 8 //where 是元素的条件
// select m.Name ; //表示m的结果返回 只输出名字
// 联合查询 现在masterList中查询 后和kongfuList中的每个结果对应3*3=9
//var res = from m in masterList
// from k in kongfuList
// where m.KongFu == k.Name && k.Power > 90 //限制条件 所学功夫的名字
// // orderby m.age descending //表示反向排列
// orderby m.Level >8 && m.Menpai=="丐帮" //按照多个字段进行排序,如果字段的属性相同,就按照第二个属性
// select m; //所学功夫大于90 的大侠
//select new { master = m, kongfu = k }; //输出2个结果
//联合查询的超级写法 这种用法很简洁,但是很难理解,因为有委托lamder表达式的纯在,记住这用法就好
// var res = masterList.SelectMany(m=>kongfuList ,(m,k) =>new {master=m,kongfu=k})
// .Where (x=>x.master.KongFu==x.kongfu.Name&&x.kongfu .Power>90);//x代表(m,k),对master和kongfu限制
//join on 联合查询
//var res = from m in masterList
// join k in kongfuList on m.KongFu equals k.Name
// where k.Power > 90
// select new { master = m, kongfu = k };
//连个分组查询 能够显示有多少人学一种功夫
//var res = from k in kongfuList
// join m in masterList on k.Name equals m.KongFu
// into groups
// orderby groups.Count()
// select new { kong = k, count = groups.Count() };
// 按照功夫分组,显示的是学功夫人的总数,功夫名称
//var res = from m in masterList
// group m by m.KongFu
// into g
// select new { count = g.Count(), key = g.Key };
///
// bool res = masterList.All(m => m.Menpai == "丐帮"); //判断所有元素满足条件
// bool res = masterList.Any(m => m.Menpai == "丐帮"); //判断是否有一个元素满足条件
foreach (var temp in res) //游例每个标量,输出的是类名而不是数据,必须转换成ToString方法格式化
{
Console.WriteLine(temp);
}
Console.ReadKey();
//用resharp 的alt+insert里的自动ToString方法完成
}
}
}