在下面的示例中,为什么产品为空?
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;
}
}
}
答案 0 :(得分:6)
其中返回 IEnumerable 而不是单个结果,并且使用 as 不会抛出异常而只是将其强制转换为null,您需要使用 SingleOrDefault()
return products.Where(p => p.ProductNumber == productNumber).SingleOrDefault();
答案 1 :(得分:1)
不要将其作为产品投射,它已经是产品。
返回products.Where(p =&gt; p.ProductNumber == productNumber).FirstOrDefault()
Null表示它不存在,返回的对象会被发现。
试试。