Havemose Havemose - 22 days ago 5
C# Question

Stepping out of foreach after finding right productID

Each of our products are based on a certain categoryID

When looping through our products it has to first find the product within that category (which it does) and then step out of it. The problem is that when it has gone through the foreach the first time (finding the right prouducts) it does not step out, it just keeps going through it finding the remainding products with other categoryIDs.

How do we solve this?

(We are using C# - Entity Framework - MSSQL)

CHEERS!

public ActionResult Index(int id)
{
var m = new Models.Product.Index();

//m.DisplayName = "Produkter";
//var scp = db.SCPconnection.FirstOrDefault(s => s.CategoryID == id);
//if (id == scp.ProductID)
{

foreach (var item in db.Product.OrderBy(p => p.ProductName))
{
var mp = new Models.Product.ModelProduct();
mp.SectorName = item.ProductName;
mp.ProductID = item.ProductID;
mp.DetailsUrl = item.Details;
m.AllProducts.Add(mp);
}
}
return View(m);
}

Answer

The break keyword immediately exits the foreach at that point. Code after the break and remaining iteration items will NOT be processed.

public ActionResult Index(int id)
{
    var m = new Models.Product.Index();

        foreach (var item in db.Product.OrderBy(p => p.ProductName))
        {
            var mp = new Models.Product.ModelProduct();
            mp.SectorName = item.ProductName;
            mp.ProductID = item.ProductID;
            mp.DetailsUrl = item.Details;
            m.AllProducts.Add(mp);

           if (item.ProductDI == id) 
               break;
        }
    }
    return View(m);
}