LINQ,语言集成查询(Language Integrated Query)是一组用于c#和Visual Basic语言的扩展。它允许编写C#或者Visual Basic代码以查询数据库相同的方式操作内存数据。
他有一些关键字 orderby,from,join,let ,select,group等
下面有简单的例子
int[] numbers = new int[] { 5,1, 2, 3, 4, 6 };
IEnumerable<int> oddnumbers = from num in numbers //int型可枚举,可用var代替,隐式识别类型
where num % 2 != 0
orderby num
select num;
从numbes里选出的每个num,得到条件是num对2取余不等于0,默认上升排序(有ascending升序,dscending降序两个关键字),然后选出num;
关于join和group关键字
定义两个类
class emplory
{
public string name {set;get;}
public int age{get;set;}
}
class em
{
public int Id {set;get;}
public string name{set;get;}
public int height{set;get;}
}
然后定义两个泛型列表
List<emplory> emplorys = new List<emplory>();
emplorys.Add(new emplory() { name = "Jack", age = 25 });
emplorys.Add(new emplory() { name = "LIlei", age = 24 });
emplorys.Add(new emplory() { name = "Hanmeimei", age = 25 });
ObservableCollection<em> emp = new ObservableCollection<em>();
emp.Add(new em() { Id = 5, height = 175, name = "Jack" });
emp.Add(new em() { Id = 6, height = 185, name = "LIlei" });
emp.Add(new em() { Id = 7, height = 175, name = "Hanmeimei" });
ObservableCollection是实现了INotifyChanged接口的,拥有改变通知机制。使用join关键字将两个列表连接,然后输出结果,它是根据两个列表有相同的项作为连接条件
var res = from c in emplorys
join e in emp on c.name equals e.name
select new { Name = c.name, age = c.age, id = e.Id, heigh = e.height };
foreach(var e in res)
{
Console.WriteLine("id:{0} age:{1} name:{2} height:{3}", e.id, e.age, e.Name, e.heigh);
}
group 是将列表中拥有相同项的组合成一组
var employer = from emplotyer in emplorys
group emplotyer by emplotyer.age into agegroup
where agegroup.Count() >= 2
select new { age = agegroup.Key, count = agegroup.Count() };
foreach(var e in employer)
{
Console.WriteLine(e.age +" "+ e.count);
}
将列表的项通过年龄进行分组得到agegroup,然后选出个数大于等于2的组,再得到age的值,和数量。
let关键字
string[] seyhello = new string[] { "Hello everyone", "welcome to Happy home", "Let us go" };
var s = from e in seyhello
let f = e.Split(' ')
from g in f
let h = g.ToUpper()
select h;
foreach(var k in s)
{
Console.WriteLine(k);
}
let可以有中间变量的使用方式。用空格分割,再全部变为大写。