1.LINQ语句
创建一个类,在这个类中重写了ToString方法,在直接打印类的时候打印类中的属性
class Master
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return string.Format("Id:{0},Name:{1},Age{2}",Id,Name,Age);
}
}
在Main函数中使用var型的变量存储结果,通过from先确定查询的对象在那个集合,再通过where(&&添加并列条件)确定范围,最后返回临时存储的值
class Program
{
static void Main(string[] args)
{
var master = new List()
{
new Master() {Id = 1,Name = "HM",Age = 18 },
new Master() {Id = 2,Name = "HR",Age = 20 },
new Master() {Id = 3,Name = "CEO",Age = 22 },
};
var res = from m in master
where m.Age>18
select m;
foreach(var temp in res)
{
Console.WriteLine(temp);
}
Console.ReadKey();
}
}
上面是使用LINQ语句,下面是使用扩展方法。拓展方法调用Where方法传递一个方法,将这个方法将集合中的每一个元素作为参数,返回返回一个bool值,最后将符合的master变量返回。
class Program
{
static void Main(string[] args)
{
var master = new List()
{
new Master() {Id = 1,Name = "HM",Age = 18 },
new Master() {Id = 2,Name = "HR",Age = 20 },
new Master() {Id = 3,Name = "CEO",Age = 22 },
};
var res = master.Where(Test1);
foreach(var temp in res)
{
Console.WriteLine(temp);
}
Console.ReadKey();
}
static bool Test1(Master master)
{
if (master.Age > 18)
{
return true;
}
else return false;
}
}
2.联合查询
在查询的得时候从多个表进行查询,
eg:a、b表,a中的每一个对象会和b中的每一个对象匹配一边
拓展方法
var res = master.SelectMany(m => kongfu, (m, k) => new { master = m, kongfu = k })
.Where(x => x.master.Name == x.kongfu.Name);
3.对结果进行排序
orderby 关键字 对关键字进行排序,后面加上descending,进行倒叙
4.Join on联合查询
将master中name和kongfu中name相同的进行连接
var res = from m in master
join k in kongfu on m.Name equals k.Name
select new { master1 = m, kongfu1 = k };
5.对结果进行分组操作into groups
var res = from k in kongfu
join m in master on k.Name equals m.Name
into groups
orderby groups.Count()
select new { kongfu = k, count = groups.Count() };
通过into进行分组
6.对结果进行分组操作
var res = from m in master
group m by m.Age into g
select new { count = g.Count(), g.Key };//g.key Key表示是按照那个属性分的组
7.量词操作符 any all
bool res1 = master.Any(m => m.Age > 18);
判断集合中是否满足某个条件,any是其中有一个满足条件,返回true。