C#学习笔记五: C#3.0Lambda表达式及Linq解析

最早使用到Lambda表达式是因为一个需求:
如果一个数组是:int[] s = new int[]{1,3,5,9,14,16,22};
例如只想要这个数组中小于15的元素然后重新组装成一个数组或者直接让s返回一个新数组该怎么截取?

最开始的想法就是将这个s遍历一遍然后判断下再来重新组装成新的数组.好麻烦是不是? 于是便百度到了一个叫做Lambda的东西, 所以用了之后效果如下:

 class Program
{
static void Main(string[] args)
{
int[] s = new int []{ ,,,,,, };
var result = from n in s where n < select n;
int[] b = result.ToArray();
for (int i = ; i < b.Length; i++)
{
Console.WriteLine(b[i]);
}
Console.ReadKey();
}
}

打印结果如我们所想: 1, 3, 5, 9, 14.

剩下的就是在真实的项目中接触到的, 在这里只是作为举例, 不做细致讲解:

 var splitTexts = cmbValidationText.Split(new string[] { IncidentConstant.Comma },
            StringSplitOptions.RemoveEmptyEntries);
if (cmbValidation.Items != null && cmbValidation.Items.Count > )
{
foreach (var splitText in splitTexts)
{
bool valid = cmbValidation.Items.Any(item => (item != null) && (item.Enabled) &&
            (string.Equals(splitText, item.Prefix, StringComparison.OrdinalIgnoreCase))); if (!valid)
{
invalidText += splitText.ToString() + CommaAndBlank;
isInvalidTextExist = true;
}
}
} var categoryAndCapabilities = capabilities.Select(item =>
{
PRResponseCategory category = null;
PRCapability prCapability = provisioningManager.GetPRCapabilityByKey(item.PRCapabilityKey.
            GetValueOrDefault());
if (prCapability != null)
{
category = statusMonitorDao.GetResponseCategoryByKey(prCapability.ResponseCategoryKey.
            GetValueOrDefault());
}
return new { Category = category, PRCapability = prCapability, Capability = item };
})
.Where(item => (item != null && item.Category != null && item.PRCapability != null))
.OrderBy(item => item.Category.Code)
.ThenBy(item => item.PRCapability.AllowNumeric.GetValueOrDefault() ? : )
.ThenBy(item => item.PRCapability.CapabilityCode)
.GroupBy(item => item.PRCapability.ResponseCategoryKey.GetValueOrDefault())
.ToDictionary(grouping => grouping.Key, grouping => grouping.ToList());

这里会不会觉得很神奇? 那么下面就开始Lambda及Linq之旅吧.

1,Linq解析
Linq是Language Integrated Query的缩写, 即"语言集成查询"的意思. 它主要包含4个组件: Linq to Object, Linq to XML, Linq to DataSet 和Linq to Sql.
更多详细内容可以查看一个国外网站: http://www.dotnetperls.com/linq

下面步入正题:

(1),查询表达式

查询表达式是一种使用查询语法表示的表达式,它用于查询和转换来自任意支持LINQ的数据源中的数据。查询表达式使用许多常见的C#语言构造,易读简洁,容易掌握。它由一组类似于SQL或XQuery的声明性语法编写的子句组成。每一个子句可以包含一个或多个C#表达式。这些C#表达式本身也可能是查询表达式或包含查询表达式。

查询表达式必须以from子句开头,以select或group子句结束。第一个from子句和最后一个select子句或group子句之间,可以包含一个活多个where子句、let子句、join子 句、orderby子句和group子句,甚至还可以是from子句。它包括8个基本子句,具体说明如下所示。
●from子句:指定查询操作的数据源和范围变量。
●select子句:指定查询结果的类型和表现形式。
●where子句:指定筛选元素的逻辑条件。
●let子句:引入用来临时保存查询表达式中的字表达式结果的范围变量。
●orderby子句:对查询结果进行排序操作,包括升序和降序。
●group子句:对查询结果进行分组。
●into子句:提供一个临时标识符。join子句、group子句或select子句可以通过该标识符引用查询操作中的中坚结果。
●join子句:连接多个用于查询操作的数据源。

1.1,select,from, where子句:
示例1
下面创建一个查询表达式query,该查询表达式查询arr数组中的每一个元素。
int[]arr =new int[]{0,1,2,3,4,5,6,7,8,9};

分析1

 class Program
{
static void Main()
{
int[] arr = new int[] { , , , , , , , , , };
var query = from n in arr
select n;
foreach (var element in query)
Console.WriteLine(element);
Console.ReadKey();
}
}

C#学习笔记五: C#3.0Lambda表达式及Linq解析

示例2
下面创建一个查询表达式query2.该查询表达式查询arr数组中大于6的元素。

 class Program
{
static void Main()
{
int[] arr = new int[]{,,,,,,,,,};
var query = from n in arr
where n >
select n;
foreach (var element in query)
Console.WriteLine(element);
Console.ReadKey();
}
}

C#学习笔记五: C#3.0Lambda表达式及Linq解析

分析2
变量只是保存查询操作,而不是查询的结果。当查询表达式执行查询操作时,才会计算该查询表达式的结果。以上两个变量的类型都属于集合类型。

示例3
下面创建一个查询表达式query。该查询表达式包含两个from子句,他们分别查询两个独立的数据源;arr1数组和arr2数组。最后,使用select子句计算当前元素的和。

 class Program
{
static void Main()
{
int[] arr1= new int[] {,,,,,,,,,};
int[] arr2=new int[] {,,,,,,,,,};
var query = from a in arr1
from b in arr2
select a +b; foreach (var element in query)
Console.WriteLine(element);
Console.ReadKey();
}
}

分析3
包含符合from子句的查询表达式
在查询表达式中,有可能查询表达式的数据源中的每一个元素本身也作为该查询表达式的数据源。那么要查询数据源中的每一个元素中的元素,则需要使用符合from子句。符合from子句类似于嵌套的foreach语句。

1.2,let子句
let子句用来创建一个新的范围变量,它用于存储子表达式的结果。let子句使用编程者提供的表达式的结果初始化该变量。一旦初始化了该范围变量的值,它就不能用于存储其他的值。

示例
下面创建一个查询表达式query。该查询表达式从arr数组中查询为偶数的元素。

 class Program
{
static void Main(string[] args)
{
int[] arr = new int[] {,,,,,,,,,};
var query = from n in arr
let isEven = (n % == ? true : false)
where isEven
select n; foreach (var element in query)
Console.WriteLine(element);
Console.ReadKey();
}
}

C#学习笔记五: C#3.0Lambda表达式及Linq解析

分析
"return n%2==0?true:false"表达式判断n元素是否为偶数。如果是,则返回true,否则返回false。“let isEven =return n%2==0?true:false”表达式使用let子句创建新的范围变量isEven,用来保存"return n%2==0?true:false"表达式的结果。"where isEven"表达式使用where子句筛选isEven的值为true的元素。

1.3,orderby子句
orderby子句可使返回的查询结果按升序或者降序排序。升序由关键字ascending指定,而降序由关键字descending指定。
注意:orderby子句默认排序方式为升序。

示例
下面创建一个查询表达式query。该查询表达式从arr数组中查询大于1且小于6的元素,并且按照n元素对查询结果进行降序排序。

 class Program
{
static void Main()
{
int[] arr = new int[]{,,,,,,,,,};
var query = from n in arr
where n> && n<
orderby n descending
select n ;
foreach (var element in query)
Console.WriteLine(element);
Console.ReadKey();
}
}

C#学习笔记五: C#3.0Lambda表达式及Linq解析

分析
orderby子句可以包含一个或多个排序表达式,各个排序表达式使用逗号(,)分隔。

1.4, group子句
group子句用来将查询结果分组,并返回一对象序列。这些对象包含零个或更多个与改组的key值匹配的项,还可以使用group子句结束查询表达式。
注意:每一个分组都不是单个元素,而是一个序列(也属于集合)。

示例
下面创建一个查询表达式query。该查询表达式从arr数组中查询大于1且小于6的元素,并且按照n%2表达式的值对查询结果进行分组。

 class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { , , , , , , , , , };
var query = from n in arr
where n > && n <
group n by n % ; foreach (var element in query)
Console.WriteLine(element);
Console.ReadKey();
}
}

C#学习笔记五: C#3.0Lambda表达式及Linq解析

分析
query查询表达式的结果是一个序列(类型为IEnumerable<IGrouping<int,int>>),该序列的元素类型为IGrouping<int,int>.其实,该查询结果中的元素也是一个序列。

1.5, into子句 
下面创建一个查询表达式query。该查询表达式从arr数组中查询大于1且小于6的元素,并且按照n%2表达式的值对查询结果进行分组。该查询表达式的具体说明如下所示:
where n>1 && n<6:指定筛选大于1且小于6的元素。
group n by n%2 into g: 按照n%2表达式的值对查询结果进行分组(0和0一组, 1和1 一组),并使用into子句创建临时标识符g。该临时标识符临时保存分组结果。
from sn in g:从g标识符指定的每一个分组中查询sn元素。
select sn:表示查询sn元素。

 class Program
{
static void Main()
{
int[] arr = new int[]{,,,,,,,,,};
var query = from n in arr
where n>&& n<
group n by n% into g
from sn in g
select sn;
foreach (var element in query)
Console.WriteLine(element);
Console.ReadKey();
}
}

C#学习笔记五: C#3.0Lambda表达式及Linq解析

分析
上述查询表达式的查询结果包括4个元素,依次为2、4、3和5

1.6, join子句
join子句用来连接两个数据源,即设置两个数据源之间的关系。join子句支持以下3种常见联接方式。
内部联接:元素的链接关系 必须同时满足两个数据源,类似于SQL语句中的inner join子句。
分组联接:包含into子句的join子句。
左外部联接:元素的链接关系必须满足联接中的左数据源,类似于SQL语句中的left join子句。

内部联接:join子句的内部联接要求两个数据源都必须存在相同的值,即两个数据源都必须存在满足联接关系的元素。

示例
下面创建一个查询表达式query。该查询表达式使用join子句联接了arra和arrb数组,具体说明如下。
创建arra数组,它包含10个元素(0~9)。
创建arrb数组,它包含5个元素(0、2、4、6和8)。
创建query查询。
from a in arra:从arra数组中选择元素,并表示为a。
where a < 7: 从arra数组中选择小于7的元素
join b in arrb on a equals b: 将arra和arrb数组进行联接,同时满足a和b相等的条件。其中,b元素是arrb数组中的元素。
select a: 选择a元素。

 class Program
{
static void Main()
{
int[] arra = new int[] {,,,,,,,,,};
int[] arrb = new int[]{,,,,};
var query = from a in arra
where a <
join b in arrb on a equals b
select a;
foreach (var element in query)
Console.WriteLine(element);
Console.ReadKey();
}
}

C#学习笔记五: C#3.0Lambda表达式及Linq解析

分析
上述查询表达式首先选择小于7的元素,(包括0~6),然后再与arrb数组进行联接,并获取既包含在{0,1,2,3,4,5,6}集合中,又包含在arrb数组中的元素。最终,查询表达式的结果包含4个元素(0、2、4和6)
分组联接:join子句的分组联接包含into子句的join子句的链接。它将左数据源与右数据源的元素一次匹配。左数据源的所有元素都出现在查询结果中。若在右数据源中找到匹配项,则使用匹配的数据,否则用空表示。

(2),使用Linq to XML查询XML文件
在Linq提出之前, 我们可以使用XPath来查询XML文件, 但是用XPath时必须首先知道XML文件的具体结构, 而使用Linq to XML则不需要知道这些.
而且Linq to XML的代码还更加简洁.

 class Program
{
//初始化xml数据
private static string xmlString =
"<Persons>" +
"<Person Id = '1'>" +
"<Name>Barry Wang</Name>" +
"<Age>18</Age>" +
"</Person>" +
"<Person Id = '2'>" +
"<Name>Tony Jia</Name>" +
"<Age>20</Age>" +
"</Person>" +
"<Person Id = '3'>" +
"<Name>Anson Shen</Name>" +
"<Age>19</Age>" +
"</Person>" +
"</Persons>"; static void Main(string[] args)
{
Console.WriteLine("使用Linq方法来对XML文件查询, 查询结果是: ");
UsingLinqLinqToXmlQuery();
Console.ReadKey();
} //使用Linq来对XML文件进行查询
private static void UsingLinqLinqToXmlQuery()
{
//导入XML文件
XElement xmlDoc = XElement.Parse(xmlString); //创建查询, 获取姓名为"李四"的元素
var queryResults = from element in xmlDoc.Elements("Person")
where element.Element("Name").Value == "Barry Wang"
select element; //输出查询结果
foreach (var xele in queryResults)
{
Console.WriteLine("姓名为: " + xele.Element("Name").Value + "Id为: " + xele.Attribute("Id").Value);
}
}
}

C#学习笔记五: C#3.0Lambda表达式及Linq解析

Linq to DataSet其实都和Linq to Object 类似, 这里就不在讲解了.更多内容在以下两个链接:
MSDN之Linq讲解
Linq操作合集

2,Lambda表达式
Lambda表达式可以理解为一个匿名方法, 它可以包含表达式和语句, 并且用于创建委托或转换表达式树.
在使用Lambda表示式时, 都会使用"=>"运算符(读作goes to), 该运算符的左边是匿名方法的输入参数, 右边则是表达式或语句块.

这里主要列举下Linq和Lambda表达式的一些区别:

LINQ的书写格式如下:  
  from 临时变量 in 集合对象或数据库对象  
  where 条件表达式   
  [order by条件]   
  select 临时变量中被查询的值  
  [group by 条件]

Lambda表达式的书写格式如下:
  (参数列表) => 表达式或者语句块

其中:参数个数:可以有多个参数,一个参数,或者无参数。
参数类型:可以隐式或者显式定义。
表达式或者语句块:这部分就是我们平常写函数的实现部分(函数体)。 

1.查询全部

查询Student表的所有记录。

 select * from student
Linq:
from s in Students
select s
Lambda:
Students.Select( s => s)

2 按条件查询全部:

查询Student表中的所有记录的Sname、Ssex和Class列。

 select sname,ssex,class from student
Linq:
from s in Students
select new {
s.SNAME,
s.SSEX,
s.CLASS
}
Lambda:
Students.Select( s => new {
SNAME = s.SNAME,SSEX = s.SSEX,CLASS = s.CLASS
})

3.distinct 去掉重复的

查询教师所有的单位即不重复的Depart列。

 select distinct depart from teacher
Linq:
from t in Teachers.Distinct()
select t.DEPART
Lambda:
Teachers.Distinct().Select( t => t.DEPART)

4.连接查询 between and

查询Score表中成绩在60到80之间的所有记录。

 select * from score where degree between  and
Linq:
from s in Scores
where s.DEGREE >= && s.DEGREE <
select s
Lambda:
Scores.Where(
s => (
s.DEGREE >= && s.DEGREE <
)
)

5.在范围内筛选 In

 select * from score where degree in (,,)
Linq:
from s in Scores
where (
new decimal[]{,,}
).Contains(s.DEGREE)
select s
Lambda:
Scores.Where( s => new Decimal[] {,,}.Contains(s.DEGREE))

6.or 条件过滤

查询Student表中"95031"班或性别为"女"的同学记录。

 select * from student where class ='' or ssex= N'女'
Linq:
from s in Students
where s.CLASS == ""
|| s.CLASS == "女"
select s
Lambda:
Students.Where(s => ( s.CLASS == "" || s.CLASS == "女"))

7.排序

以Class降序查询Student表的所有记录。

 select * from student order by Class DESC
Linq:
from s in Students
orderby s.CLASS descending
select s
Lambda:
Students.OrderByDescending(s => s.CLASS)

8.count()行数查询

 select count(*) from student where class = ''
Linq:
( from s in Students
where s.CLASS == ""
select s
).Count()
Lambda:
Students.Where( s => s.CLASS == "" )
.Select( s => s)
.Count()

9.avg()平均

查询'3-105'号课程的平均分。

 select avg(degree) from score where cno = '3-105'
Linq:
(
from s in Scores
where s.CNO == "3-105"
select s.DEGREE
).Average()
Lambda:
Scores.Where( s => s.CNO == "3-105")
.Select( s => s.DEGREE).Average()

10.子查询
查询Score表中的最高分的学生学号和课程号。

 select distinct s.Sno,c.Cno from student as s,course as c ,score as sc
where s.sno=(select sno from score where degree = (select max(degree) from score))
and c.cno = (select cno from score where degree = (select max(degree) from score))
Linq:
(
from s in Students
from c in Courses
from sc in Scores
let maxDegree = (from sss in Scores
select sss.DEGREE
).Max()
let sno = (from ss in Scores
where ss.DEGREE == maxDegree
select ss.SNO).Single().ToString()
let cno = (from ssss in Scores
where ssss.DEGREE == maxDegree
select ssss.CNO).Single().ToString()
where s.SNO == sno && c.CNO == cno
select new {
s.SNO,
c.CNO
}
).Distinct()

11.分组 过滤

查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。

 select avg(degree) from score where cno like '3%' group by Cno having count(*)>=
Linq:
from s in Scores
where s.CNO.StartsWith("")
group s by s.CNO
into cc
where cc.Count() >=
select cc.Average( c => c.DEGREE)
Lambda:
Scores.Where( s => s.CNO.StartsWith("") )
.GroupBy( s => s.CNO )
.Where( cc => ( cc.Count() >= ) )
.Select( cc => cc.Average( c => c.DEGREE) )
Linq: SqlMethod
like也可以这样写:
s.CNO.StartsWith("") or SqlMethods.Like(s.CNO,"%3")

12.分组

查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。

 select avg(degree) from score where cno like '3%' group by Cno having count(*)>=
Linq:
from s in Scores
where s.CNO.StartsWith("")
group s by s.CNO
into cc
where cc.Count() >=
select cc.Average( c => c.DEGREE)
Lambda:
Scores.Where( s => s.CNO.StartsWith("") )
.GroupBy( s => s.CNO )
.Where( cc => ( cc.Count() >= ) )
.Select( cc => cc.Average( c => c.DEGREE) )
Linq: SqlMethod
like也可以这样写:
s.CNO.StartsWith("") or SqlMethods.Like(s.CNO,"%3")

13. 多表查询

 select sc.sno,c.cname,sc.degree from course as c,score as sc where c.cno = sc.cno
Linq:
from c in Courses
join sc in Scores
on c.CNO equals sc.CNO
select new
{
sc.SNO,c.CNAME,sc.DEGREE
}
Lambda:
Courses.Join ( Scores, c => c.CNO,
sc => sc.CNO,
(c, sc) => new
{
SNO = sc.SNO,
CNAME = c.CNAME,
DEGREE = sc.DEGREE
})

14,关联多条件查询

现在加上两张表的关联多条件查询, 只有Linq和Lambda表达式

如下是一个两张表关联查询的Linq及Lambda表达式的Demo, 仅供大家参考.

 class Program
{
static void Main()
{
DataTable tableA = new DataTable();
tableA.Columns.Add("Name", typeof(string));
tableA.Columns.Add("Age", typeof(int));
tableA.Columns.Add("Score", typeof(int)); DataTable tableB = new DataTable();
tableB.Columns.Add("Name", typeof(string));
tableB.Columns.Add("Age", typeof(int));
tableB.Columns.Add("Score", typeof(int)); tableA.Rows.Add("Barry", , );
tableA.Rows.Add("Tony", , );
tableA.Rows.Add("Tom", , );
tableA.Rows.Add("Brad", , ); tableB.Rows.Add("Kitty", , );
tableB.Rows.Add("Tom", , );
tableB.Rows.Add("Jhon", , );
tableB.Rows.Add("Brad", , ); //单表查询
var singleQuery = tableA.AsEnumerable().Where(stu => stu.Field<int>("Age") > );
foreach (var item in singleQuery)
{
Console.WriteLine("Case 1 query result: Age {0}, Name {1}", item.Field<int>("Age"),
              item.Field<string>("Name").ToString());
} //Linq:两张表的关联查询
var doubleQuery = from a in tableA.AsEnumerable()
from b in tableB.AsEnumerable()
where a.Field<string>("Name") == b.Field<string>("Name") &&
a.Field<int>("Age") != b.Field<int>("Age")
orderby a.Field<string>("Name"), a.Field<int>("Score")
select new
{
Name = a.Field<string>("Name"),
A_Age = a.Field<int>("Age"),
B_Age = b.Field<int>("Age")
};
foreach (var item in doubleQuery)
{
Console.WriteLine("Case 2 query result: Name {0}, tableA_Age {1}, tableB_Age {2}",
               item.Name, item.A_Age, item.B_Age);
} //Lambda:两张表的关联查询
var query = tableA.AsEnumerable()
.Join(tableB.AsEnumerable(),
a => a.Field<string>("Name"),
b => b.Field<string>("Name"),
(a, b) => new
{
a = a,
b = b
})
.Where(c => (c.a.Field<int>("Age") != c.b.Field<int>("Age")))
.OrderBy(d => d.a.Field<string>("Name"))
.ThenBy(e => e.a.Field<int>("Score"))
.Select(f => new
{
Name = f.a.Field<string>("Name"),
A_Age = f.a.Field<int>("Age"),
B_Age = f.b.Field<int>("Age"),
A_Score = f.a.Field<int>("Score"),
B_Score = f.a.Field<int>("Score")
});
foreach (var item in query)
{
Console.WriteLine("Case 3 query result: Name {0}, tableA_Age {1}, tableB_Age {2}, tableA_Score {3},
              tableB_Score {}",item.Name, item.A_Age, item.B_Age, item.A_Score, item.B_Score);
}
Console.ReadKey();
}
}

解析:

  首先可以看出来, Lambda表达式对于这种多表多条件的查询写法的易读性明显没有Linq高, 所以 还是建议用Linq去写. 运行结果如下图:

C#学习笔记五: C#3.0Lambda表达式及Linq解析

上一篇:计算机学院大学生程序设计竞赛(2015’12) 1004 Happy Value


下一篇:golang mysql连接