In the example below, why is product null?
开发者_JAVA技巧using System.Collections.Generic;
using System.Linq;
namespace TestEventsds343
{
public class Program
{
static void Main(string[] args)
{
Product product = Product.LoadProduct(222);
}
}
public class Product
{
public int ProductNumber { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public static Product LoadProduct(int productNumber)
{
List<Product> products = new List<Product>();
products.Add(new Product { ProductNumber = 111, Name = "Intel CPU", Description = "Newest model, very fast." });
products.Add(new Product { ProductNumber = 222, Name = "Philips Monitor", Description = "22-inch, very nice." });
products.Add(new Product { ProductNumber = 333, Name = "Sony Camera", Description = "10 Megapixels, sharp pictures." });
return products.Where(p => p.ProductNumber == productNumber) as Product;
}
}
}
Where returns an IEnumerable not a single result and using as doesn't throw an exception and just casts it to null, you need to use SingleOrDefault()
return products.Where(p => p.ProductNumber == productNumber).SingleOrDefault();
Don't cast it as Product, it already is a product.
return products.Where(p => p.ProductNumber == productNumber).FirstOrDefault()
Null would indicate it doesn't exist, an object returned would be it found something.
Try that.
精彩评论