这一节大家共同学习下LINQ的基本用法,主要包括LINQ的分组,排序,和内外连接。
1.分组
基本语法: group element by key
element 表示查询结果返回的元素,key表示分组条件。group子句返回的类型为IGrouping<TKey,TElement>的查询结果。
IGrouping<TKey,TElement>可以看成一个hashtable内部嵌套一个list列表的数据结果. 其中TElement就是一个list
我们看下面的一个事例,下面这个实例演示根据性别对用户进行分组
代码
public class User { public User(string userName,string sex,int age) { UserName = userName; Sex = sex; Age = age; } public string UserName { get; set; } public string Sex { get; set; } public int Age { get; set; } }
private void button1_Click(object sender, EventArgs e) { User[] users = { new User("刘德华","男",40), new User("张学友","男",30), new User("张曼玉","女",35), new User("杨幂","女",53) }; var query1 = from var1 in users group var1 by var1.Sex; string str = ""; foreach (var item in query1) { str += item.Key + "\r\n"; foreach (var user in item) { str += user.UserName + "--" + user.Sex + "--" + user.Age.ToString() + "\r\n"; } } textBox1.Text = str; }
效果图
以上是简单的分组,如果需要对分组结果进行排序,需要把分组结果保存到一个临时变量中
语法: group element by key into temp
以下是按年龄从小到大的排序:
代码
User[] users = { new User("刘德华","男",40), new User("张学友","男",30), new User("张曼玉","女",35), new User("杨幂","女",53) }; var query1 = from var1 in users group var1 by var1.Age into temp orderby temp.Key descending select temp; string str = ""; foreach (var item in query1) { str += item.Key + "\r\n"; foreach (var user in item) { str += user.UserName + "--" + user.Sex + "--" + user.Age.ToString() + "\r\n"; } } textBox1.Text = str;
效果图
2.排序
在linq中排序使用orderby
语法 orderby elment descending||ascending
ascending表示升序,descending表示降序
下面这个DEMO演示按年龄从大到小排序
代码:
User[] users = { new User("刘德华","男",40), new User("张学友","男",30), new User("张曼玉","女",35), new User("杨幂","女",53) }; var query1 = from var1 in users orderby var1.Age descending select var1; string str = ""; foreach (var item in query1) { str += item.UserName + "--" + item.Age + "\r\n"; } textBox1.Text = str;
效果图
3.内连接
内连接查询就是根据一定的条件查询两个数据源中都存在的元素
语法: join elment in datasource on re1 equals re2
以下代码查找两个数组中都存在的元素。
代码:
private void button3_Click(object sender, EventArgs e) { //查询两个数组中都存在的元素 int[] arrOne = { 10,20,30,6,8}; int[] arrTwo = { 10,4,6,8,90,3}; var query = from re1 in arrOne join re2 in arrTwo on re1 equals re2 select new { re1 = re1, re2 = re2 }; foreach (var item in query) { Console.WriteLine(item); } }
查询结果:
{ re1 = 10, re2 = 10 } { re1 = 6, re2 = 6 } { re1 = 8, re2 = 8 }
4.左连接
左连接和SQL中的左连接类似,返回第一个结果集中的所有元素。
下面的代码演示使用左连接,左连接要用到defaultempty()方法,此方法从列表中获取指定元素,如果列表为空,返回默认值
代码
private void button4_Click(object sender, EventArgs e) { //左连接 int[] arrOne = { 10, 20, 30, 6, 8 }; int[] arrTwo = { 10, 4, 6, 8, 90, 3 }; var query = from re1 in arrOne join re2 in arrTwo on re1 equals re2 into temgrp from grp in temgrp.DefaultIfEmpty() select new { re1 = re1, re2 = grp }; foreach (var item in query) { Console.WriteLine(item); } }
查询结果
{ re1 = 10, re2 = 10 } { re1 = 20, re2 = 0 } { re1 = 30, re2 = 0 } { re1 = 6, re2 = 6 } { re1 = 8, re2 = 8 }