tags:

views:

86

answers:

2

In the example below, why is product null?

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;
        }
    }
}
+6  A: 

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();
Stan R.
Just as clarification, `Where` returns `IEnumerable`, not a collection. This isn't just a semantic difference; *there is no actual collection*.
Adam Robinson
@Adam, you are correction, I knew what I meant in my head....if you know what I mean. To me it was semantics, but I really should clarify better. Edited.
Stan R.
Right -- the clear way to remember this is that Where returns *an object that represents a filter*. It does not return *a filtered collection*, it returns *the abstract notion of "filter this collection"*. When you iterate that object, then and only then does it filter the collection.
Eric Lippert
+1  A: 

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.

TravisWhidden
its not a Product its IEnumerable<Product>
Stan R.
he is returning a Product, not an IEnumerable<Product>"static Product LoadProduct("
TravisWhidden