-1

I want to find and return the first CartLine that has a match of product in a Cart with the FindProductInCartLines(int productId) method. If occurrence can't be found return null.

However, the compiler throws an error

Cannot implicitly convert type: CartLine to Product

with the FirstOrDefault() line number.

I'm a real newbie concerning lambda functions and delegates. I thought it was already dereferenced with line.Product.Id but obviously I'm having some kind of misunderstanding.

I tried using JaredPar's answer from: Create IEnumerable<T>.Find() But I don't see the difference between my code and his.

public class CartLine 
{
    public int OrderLineId { get; set; }
    public Product Product { get; set; }
    public int Quantity { get; set; }
}

public IEnumerable<CartLine> Lines => GetCartLineList();

private List<CartLine> GetCartLineList()
{
    return new List<CartLine>();
}

public Product FindProductInCartLines(int productId)
{
    return Lines.FirstOrDefault(line => line.Product.Id == productId);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

1

When you call FirstOrDefault() it will return an object of the same type as the source, in your case that is Lines which is of type CartLine - which is why you get the error. To get the child property from the parent you need add a reference to the property to your call (allowing for nulls).

So, in your case you would need:

public Product FindProductInCartLines(int productId)
{
    return Lines.FirstOrDefault(line => line.Product.Id == productId)?.Product;
}

If you are unsure of the ?. operator you can read this answer for a great explanation.

Simply Ged
  • 8,250
  • 11
  • 32
  • 40
0
// The method return type is Product
 public Product FindProductInCartLines(int productId){
               return Lines.FirstOrDefault(line => line.Product.Id == productId);// this line return CartLine object;
           }

You should change return type of method to CartLine

 public CartLine FindProductInCartLines(int productId){
               return Lines.FirstOrDefault(line => line.Product.Id == productId);
           }

If you want it return Product

 public Product FindProductInCartLines(int productId){
               return Lines.FirstOrDefault(line => line.Product.Id == productId)?.Product;
           }
Phat Huynh
  • 772
  • 5
  • 16