2013-04-08 82 views
4

可以說我有一個數組說明代碼:使用FirstorDefault()

Product[] myProducts = new Product[] 
{ 
    new Product { ID = 1, name = "Ketchup1", category = "Sauces", price = 200.00m }, 
    new Product { ID = 2, name = "Ketchup2", category = "Sauces", price = 200.00m }, 
    new Product { ID = 3, name = "Ketchup3", category = "Sauces", price = 200.00m } 
}; 

一些項目然後可以說,我嘗試使用這種方法

public Product GetProductById(int id) 
{ 
    var product = products.FirstOrDefault((p) => p.Id == id); 
    if (product == null) 
    { 
     throw new HttpResponseException(HttpStatusCode.NotFound); 
    } 
    return product; 
} 

我必須找回從陣列中檢索項閱讀它做什麼,但我沒有得到這裏發生了什麼:

FirstorDefault(p => p.Id == id); 
+0

參見:http://msdn.microsoft.com/en-us/library/vstudio/bb311046.aspx – 2013-04-08 07:41:37

+0

它創建一個臨時變量類型的產品,然後比較其'Id'屬性與給定值 – Sandy 2013-04-08 07:41:41

+1

這是一個lambda表達式,[檢查它](http://msdn.microsoft.com/en-gb/library/bb397687.aspx) – fbstj 2013-04-08 07:41:48

回答

3

FirstOrDefault(predicate)遍歷集合,並返回該謂詞匹配第一個元素。在你的例子中,它將成爲p.Id == id的第一個元素。當沒有匹配謂詞的值時,將返回默認值(所有引用類型均爲null)。

(p) => p.Id == idlambda expression匹配Func<Product, bool> - 它需要Product類型(它的命名p)的一個參數和返回值bool

FirstOrDefault可能看起來很相似,它是eduLINQ equivalent

public static TSource FirstOrDefault<TSource>( 
    this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate) 
{ 
    // Argument validation elided 
    foreach (TSource item in source) 
    { 
     if (predicate(item)) 
     { 
      return item; 
     } 
    } 
    return default(TSource); 
} 
1

這個條件比需要滿足田間。

(p) => p.Id == id 

是lambda表達式,它給出參數p回報p.Id == ID

這就是所謂的每一個元素,直到它是真實的。

因此,product將是其中的Id給定id或零相匹配的第一個元素,如果不存在這樣