Click here to Skip to main content
15,887,821 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello I just started learning about LINQ.
I am trying to return all products which are out of stock (UnitsInStock == 0)
The code does not compile. Any help would be appreciated. Thank you!

What I have tried:

public static IEnumerable<Product> ProductsOutOfStock()
        {
            List<Product> products = Products.ProductList;

            IEnumerable<int> query = products.Where(p => p.UnitsInStock == 0 ); //CS0266

            foreach (Product p in query) //CS0030
            {
                yield return p;
            }
        }
Posted
Updated 28-Feb-22 1:57am
v3

You have declared query as IEnumerable<int>, but then you try to pass it a list of Products. Change it to IEnumerable<Product>.
 
Share this answer
 
Comments
LuckyChloe 28-Feb-22 7:37am    
Thank you. I copied that from previous task and forgot to change 🤦
Will be posting more if I get stuck again
Richard MacCutchan 28-Feb-22 7:51am    
You're welcome. When you get an error it is always worth looking up the code to see what causes it. At the very least it can give you some clues.
To add to what Richard said, the loop inside method ProductsOutOfStock is redundant, it does not add anything to your query variable. So you can simplify to

public static IEnumerable<Product> ProductsOutOfStock() {
    return products.Where(p => p.UnitsInStock == 0);}


:)
 
Share this answer
 
Comments
LuckyChloe 28-Feb-22 8:01am    
Thank you very much it indeed worked without foreach loop.
Richard MacCutchan 28-Feb-22 8:10am    
A much better answer than mine. I am still very much a novice at LINQ.
Luc Pattyn 28-Feb-22 8:31am    
I specialize in discarding code, it is a great way of reducing the bug count

D)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900