The
FirstOrDefault
extension method of
IEnumerable
interface returns the first occurance or the default value of the collection member.
var price = Products.FirstOrDefault(i => i.Name = productName).Select(i => i.price);
In this case it returns the
ProductInfo
object.
The
ProductInfo
class does not have
Select
method Hence, the .
Select
will throw error in the above statement.
So, instead of .Select(i => i.price) we have to use .Price.
ProductName
is a string, = in i.Name = productName is to be == for comparison
But, when the
List
is empty the
FirstOrDefault
returns
null
as the default value for a reference type is null and if the required product is not found say we passed
Ipad2
, the method returns null. In either case if we directly access
Price
property on the object returned by the
FindOrDefault
method, there is a chance of error. Hence, I think the better option would be
ProductInfo selectedProductInfo = Products.FirstOrDefault(p => p.Name == productName);
double price = selectedProductInfo == null ? 0 : selectedProductInfo.Price;
[EDIT]The following text inserted by Clifford Nelson[EDIT]
May not have an issue with null, and can cover with an exception. During debug can put an Debug.Asser. Can also do the following
var price = (Products.FirstOrDefault(i => i.Name = productName) ?? new Preduct()).Select(i => i.price);