查詢表達式中處理Null值
此示例演示如何處理源集合中可能的 null 值。 諸如 IEnumerable<T> 等對象集合可能包含值為 null 的元素。 如果源集合為 null 或包含值為 null 的元素,並且查詢未處理 null 值,當您執行查詢時將會引發 NullReferenceException。
var query1 =
from c in categories
where c != null join p in products on c.ID equals (p == null ? null : p.CategoryID) select new { Category = c.Name, Name = p.Name };
在 join 子句中,只要其中一個比較鍵是可以為 null 的類型,您就可以在查詢表達式中將另一個比較鍵強制轉換成可以為 null 的類型。 在下面的示例中,假定 EmployeeID 是一個列,其中包含類型為 int? 的值:
void TestMethod(Northwind db)
{
var query =
from o in db.Orders join e in db.Employees on o.EmployeeID equals (int?)e.EmployeeID select new { o.OrderID, e.FirstName }; }
在查詢表達式中處理異常
下面的示例演示如何將異常處理代碼移至查詢表達式外部。 僅當該方法不依賴於查詢的任何本地變量時,才能這樣做。
class ExceptionsOutsideQuery
{
static void Main() { // DO THIS with a datasource that might // throw an exception. It is easier to deal with // outside of the query expression. IEnumerable<int> dataSource; try { dataSource = GetData(); } catch (InvalidOperationException) { // Handle (or don't handle) the exception // in the way that is appropriate for your application. Console.WriteLine("Invalid operation"); goto Exit; } // If we get here, it is safe to proceed. var query = from i in dataSource select i * i; foreach (var i in query) Console.WriteLine(i.ToString()); //Keep the console window open in debug mode Exit: Console.WriteLine("Press any key to exit"); Console.ReadKey(); } // A data source that is very likely to throw an exception! static IEnumerable<int> GetData() { throw new InvalidOperationException(); } }
在某些情況下,對在查詢內引發的異常的最佳響應可能是立即停止執行查詢。 請注意,try 塊將 foreach 循環而不是查詢本身封閉起來。 這是因為 foreach 循環是實際執行查詢的場所。
class QueryThatThrows
{
static void Main() { // Data source. string[] files = { "fileA.txt", "fileB.txt", "fileC.txt" }; // Demonstration query that throws. var exceptionDemoQuery = from file in files let n = SomeMethodThatMightThrow(file) select n; // Runtime exceptions are thrown when query is executed. // Therefore they must be handled in the foreach loop. try { foreach (var item in exceptionDemoQuery) { Console.WriteLine("Processing {0}", item); } } // Catch whatever exception you expect to raise // and/or do any necessary cleanup in a finally block catch (InvalidOperationException e) { Console.WriteLine(e.Message); } //Keep the console window open in debug mode Console.WriteLine("Press any key to exit"); Console.ReadKey(); } // Not very useful as a general purpose method. static string SomeMethodThatMightThrow(string s) { if (s[4] == 'C') throw new InvalidOperationException(); return @"C:\newFolder\" + s; } } /* Output: Processing C:\newFolder\fileA.txt Processing C:\newFolder\fileB.txt Operation is not valid due to the current state of the object. */
參考
[1] MSDN,查詢表達式Null值處理
