tailieunhanh - Apress pro LINQ Language Integrated Query in C# 2008 phần 4

LINQ tới SQL là một sự thực thi O/RM (sự ánh sạ mối quan hệ đối tượng - object relation mapping) mà nó được kèm theo phiên bản .NET Framework "Orcas", và cho phép bạn tạo mẫu một cơ sở dữ liệu quan hệ sử dụng các lớp trong .NET. Bạn có thể truy vấn tới một csdl sử dung LINQ, cũng như update/insert/delete dữ liệu từ đó. | 160 CHAPTER 5 NONDEFERRED OPERATORS This code is functionally equivalent to the previous example. Instead of calling the Where operator to ensure a single element is in the sequence I can provide the same sequence filtering operation in the Single operator itself. This should return the only element in the input sequence whose id is 3. Here are the results Anders Hejlsberg Remember if either prototype of the Single operator ends up with no element to return an InvalidOperationException is thrown. To avoid this use the SingleOrDefault operator. SingleOrDefault The SingleOrDefault operator is similar to the Single operator except for how it behaves when an element is not found. Prototypes There are two prototypes I cover. The First SingleOrDefault Prototype public static T SingleOrDefault T this IEnumerable T source This version of the prototype returns the only element found in the input sequence. If the sequence is empty default T is returned. For reference and nullable types the default value is null. If more than one element is found an InvalidOperationException is thrown. The second prototype of the SingleOrDefault operator allows you to pass a predicate to determine which element should be returned. The Second SingleOrDefault Prototype public static T SingleOrDefault T this IEnumerable T source Func T bool predicate Exceptions ArgumentNullException is thrown if any arguments are null. InvalidOperationException is thrown if the operator finds more than one element for which the predicate returns true. Examples Listing 5-30 is an example of the first SingleOrDefault prototype where no element is found. I have to get an empty sequence to do this. I ll use the Where operator and provide a key comparison for a key that doesn t exist for this purpose. CHAPTER 5 NONDEFERRED OPERATORS 161 Listing 5-30. Calling the First SingleOrDefault Prototype Where an Element Is Not Found Employee emp .Where e 5 .SingleOrDefault emp