基本信息
LINQ (Language Integrated Query) : 语言集成查询,它运行代码以查询数据库相同的方式操作内存中的数据;
注意:LINQ 读作 lin k,而不是 lin q
基本语法格式
from 临时变量 in 实现 IEnumerable<T>接口的对象
where 条件表达式
[orderby 条件]
[group 变量 by 条件]
select 临时变量中被查询的值
例子:
int[] array1 = new int[] { 1, 2, 3, 4, 5};
var result = from a in array1
where a % 2 == 0
orderby a descending
select a;
注意:一般是以 from 开头,以 select 结束,使用 LINQ 可以减少使用 for 循环,更方便的获取集合数据中的特定数据。
排序 orderby
倒序排序:关键字是 orderby (不分开)
from a in array1
where a % 2 == 0
orderby a descending //进行倒序排序
select a;
分组 group by
分组则有所不同,格式为:group 变量 by 条件
var result = from s in student_list
group s by s.name into g // 按 name 排序,并将结果转入 g, 此时临时变量 s 的作用域结束,后续只能使用 g
select g.Count();
注意:into 后面的临时变量 g 内包含多种属性和方法,其中用的较多的有:
g.Key 分组时 by 所用的条件,如上例中为 name;
g.Max() 用于求分组后组中的最大值,用法 g.Max(x=>x.age);
g.Min() 用于求分组后组中的最小值;
按名字排序,找出年龄最大
var result = from s in student_list
group s by s.name into g
select g.Max(x => x.age);
也可以根据需要定义返回格式:new {g.Key, n1=v1, n2=v2…}
var result = from s in student_list
group s by s.name into g
select new {g.Key, max_age = g.Max(x => x.age)};
根据多个条件来分组:
new {condition1, condition2}
根据年龄和名字分组, 再找出 id 最大的:
var result = from s in student_list
group s by new { s.age, s.name } into g
select new { g.Key, max_id = g.Max(x => x.id) };
分组的条件也可以使用表达式:
new {x = expression}
根据学生的名字是否等于 “tommy” 来分成 2 组,再选出年龄最大的,此时 g.Key 为表达式的结果,True / False.
var result = from s in student_list
group s by new { v = s.name = "tommy"} into g
select new {g.Key, max_age = g.Max(x => x.age)};
扩展语法
使用静态方法来完成判断逻辑:
格式:static 修饰,返回 bool 类型
static bool odd(int a) {
if (a % 2 == 0) {
return true;
}
else {
return false;
}
}
使用:
int[] array1 = new int[] { 1, 2, 3, 4, 5};
var result = array1.Where(odd);//执行结果和上述一样
Lambda 表达式
LINQ 能实现的,全部都可以用 Lambda 来实现。
附录
学生 student 类:
public class student {
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
public student(int id, string name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("id is: ").Append(id).Append("; ");
sb.Append("name is: ").Append(name).Append("; ");
sb.Append("age is: ").Append(age).Append("; ");
return sb.ToString();
}
}