当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > LINQ学习笔记:元素操作符

ASP.NET
Web服务器控件:LinkButton控件
Web服务器控件:ListBox控件
Web服务器控件:ListItem控件
Web服务器控件:Literal控件
Web服务器控件:Panel控件
Web服务器控件:PlaceHolder控件
Web服务器控件:RadioButton控件
Web服务器控件:RadioButtonList控件
Web服务器控件:BulletedList控件
Web服务器控件:Style控件
Web服务器控件:Table控件
Web服务器控件:TableCell控件
Web服务器控件:TableRow控件
Web服务器控件:TextBox控件
Web服务器控件:XML控件
Validation服务器控件:CompareValidator控件
Validation服务器控件:CustomValidator控件
Validation服务器控件:RangeValidator控件
Validation服务器控件:RegularExpressionValidator控件
Validation服务器控件:RequiredFieldValidator控件

ASP.NET 中的 LINQ学习笔记:元素操作符


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 32 ::
收藏到网摘: n/a

元素操作符

主要方法:

First, FirstOrDefault: 返回序列中的第一个元素, 可选地匹配一个断言, 对应SQL语法为SELECT TOP 1 … ORDER BY …

Last, LastOrDefault: 返回序列中的最后一个元素, 可选地匹配一个断言, 对应SQL语法为SELECT TOP 1 … ORDER BY … DESC

Single, SingleOrDefault: 同First / FirstOrDefault, 但是如果匹配操作一个, 则抛出异常

ElementAt, ElementAtOrDefault: 返回指定位置的元素

DefaultIfEmpty: 如果输入序列没有任何元素则返回Null或者default(TSource), 对应SQL语法为OUTER JOIN

如果输入序列是空的或者没有任何元素匹配断言, 那些以“OrDefault”结尾的操作符方法返回default(TSource)而不是抛出异常

对于引用类型的元素, default(TSource) = null, 而对于值类型则是“blank” (通常是0)

First, Last, Single

参数列表:

源序列: IEnumerable

断言(Predicate)可选: TSource => bool

以下的例子演示了First和Last的用法:

 1: int[] numbers = { 1, 2, 3, 4, 5 };
 2:  
 3: int first = numbers.First(); // 1
 4:  
 5: int last = numbers.Last(); // 5
 6:  
 7: int firstEven = numbers.First (n => n % 2 == 0); // 2
 8:  
 9: astEven = numbers.Last (n => n % 2 == 0); // 4

 

以下的例子演示了First和FirstOrDefault的区别:

 1: // 抛出异常:
 2:  
 3: int firstBigError = numbers.First (n => n> 10);
 4:  
 5: // 返回0:
 6:  
 7: int firstBigNumber =numbers.FirstOrDefault(n => n > 10);

 

为了避免异常, Single精确要求只有一个元素匹配, SingleOrDefault要求0或1个元素匹配:

 1: int divisibleBy3 =
 2:  
 3: numbers.Single (n => n % 3 == 0); // 3
 4:  
 5: int divisibleBy2Error =
 6:  
 7: numbers.Single (n=> n % 2 == 0); // Error: 2 matches
 8:  
 9: int singleError =
 10:  
 11: numbers.Single (n => n> 10); // Error: no matches
 12:  
 13: int noMatches =
 14:  
 15: numbers.SingleOrDefault(n => n > 10); // 0
 16:  
 17: int divisibleBy2Error =
 18:  
 19: numbers.SingleOrDefault (n => n % 2 ==0); // Error

 

Single是元素操作族群里面最挑剔的,而FirstOrDefault和LastOrDefault是最宽容的

在LINQ to SQL当中, Single经常被用于通过主键读取表中的某一行:

 1: Customer cust =
 2:  
 3: dataContext.Customers.Single (c => c.ID== 100);

 

ElementAt

参数列表:

源序列: IEnumerable

要返回的元素索引位置: int

ElementAt从源序列中挑选第nth个元素返回:

 1: int[] numbers = { 1, 2, 3, 4, 5 };
 2:  
 3: int third = numbers.ElementAt (2); // 3
 4:  
 5: int tenthError = numbers.ElementAt (9); // Error
 6:  
 7: int tenth = numbers.ElementAtOrDefault (9); // 0

 

对于Enumerable.ElementAt, 如果输入序列实现了IList, 那么它将会使用IList的所引器, 否则将会枚举n次, 然后返回下一个元素. LINQ to SQL不支持ElementAt

DefaultIfEmpty

DefaultIfEmpty将空序列转换成null或者default(). 这在编写扁平的外部连接时经常使用, 待续!