Ling 查询表达式的基本语法很容易掌故握,它使用C#常见的语言构造,从外观看跟常用的关系型数据库查询语言SQL类似,
eg:
string[] values={"test1","wangwu","lisi","qiaoqiao"};
var value=from v in values where v.Length==4 select v;
上面码代的表达的意思是,在values 里找出长度为4的字符串,from, where,select和in这些关键字肯定不陌生吧!只是这里查询不是关系数据库,是一个对象。
Ling查询的对可以是数据库、xml流和实现了IEnumerable或者泛型IEnumerable<T>接口的集合对象,Ling表达式的关键字:from、where、select、group、into、orderby、join和let,下面就对这些关键进行一一介绍。
from 指定数据源。写ling表达式就必须from开头。先定一个GuestInfo.cs类,这个类在后面也会用到.
List<GuestInfo> glist1 = new List<GuestInfo>(){ new GuestInfo { Name="test0", Age=21, TelTable=new List<string>(){"021-45126399","021-45127399"} }, new GuestInfo { Name="test1", Age=22, TelTable=new List<string>(){"021-45126399","021-45127399"} }, new GuestInfo { Name="test2", Age=23, TelTable=new List<string>(){"021-45126399","021-45127399"} } }; List<GuestInfo> glist2 = new List<GuestInfo>(){ new GuestInfo { Name="test3", Age=24, TelTable=new List<string>(){"021-45126399","021-45127399"} }, new GuestInfo { Name="test4", Age=28, TelTable=new List<string>(){"021-45126399","021-45127399"} }, new GuestInfo { Name="test5", Age=24, TelTable=new List<string>(){"021-45126399","021-45127399"} } };
复合from的实现:
查找电话号码:021-45126399,名字:test5的记录:
var query = from guest in glist1 where guest.Name == "test2" from tel in guest.TelTable where tel == "021-45126399" select guest; foreach (var i in query) Console.WriteLine("{0}",i.Name);
输出结果:test2
多个from交叉的实现:
在glist1中找出Age=21和glist2找出Age=28的人,这里就要用到多个from了,我们可以像下面一样写代码.
var query = from guest in glist1 where guest.Age == 21 from guest2 in glist2 where guest2.Age == 28 select new { guest, guest2 }; foreach (var i in query) Console.WriteLine("{0},{1}",i.guest.Name,i.guest2.Name);
输出结果:test0,test4