Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 找到正确的productID后退出foreach_C#_Foreach - Fatal编程技术网

C# 找到正确的productID后退出foreach

C# 找到正确的productID后退出foreach,c#,foreach,C#,Foreach,我们的每种产品都基于特定的类别ID 当循环浏览我们的产品时,它必须首先找到该类别内的产品(确实如此),然后退出该类别。问题是,当它第一次通过foreach(找到合适的产品)时,它并没有走出去,而是继续通过foreach找到与其他类别产品一起重新制作的产品 我们如何解决这个问题 (我们正在使用C#-实体框架-MSSQL) 干杯 public ActionResult Index(int id) { var m = new Models.Product.Index();

我们的每种产品都基于特定的类别ID

当循环浏览我们的产品时,它必须首先找到该类别内的产品(确实如此),然后退出该类别。问题是,当它第一次通过foreach(找到合适的产品)时,它并没有走出去,而是继续通过foreach找到与其他类别产品一起重新制作的产品

我们如何解决这个问题

(我们正在使用C#-实体框架-MSSQL)

干杯

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);
    }
打破它吧

        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(condition) //if it is needed
               break;
        }

break关键字在该点立即退出foreach。中断后的代码和剩余的迭代项将不被处理

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.ProductID == id) 
               break;
        }
    }
    return View(m);
}

最好使用Where子句对特定ID进行筛选

我强烈建议优化代码,为什么您需要将所有产品的详细信息获取到业务逻辑中,而不是使用条件查询所需的内容

foreach (var item in db.Product.Where(p => p.ProductID.Equals(requiredID)).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);
    }

找到产品时使用
break