【问题标题】:Iterating through a collection without order无序遍历集合
【发布时间】:2016-01-07 16:48:55
【问题描述】:

我遇到了一个 C# 问题,希望您能帮助我。

我正在尝试找到一种方法来无顺序地访问集合的所有元素,即。同时。

 //We are in the Planification Class

public void AddProduct(ProductFinal product, DateTime date, double quantity)
    {
        if (planificationLines== null)
        {
            planificationLines= new List<planificationLine>();
        }
        PlanificationLine planificationLine= new PlanificationLigne(this, product, date, quantity);
        planificationLines.Add(planificationLine);
        ProcessPlanification(planificationLine);
    }

    public void ProcessPlanification(PlanificationLine planificationLine)
    {


        //Load all recipes
        List<Recipes> listeFT = LoadAllRecipes().ToList();


        //Change the Quantity to produce of the FinalProduct ordered in planificationLine
        planificationLine.Product.QuantityToProduce+= planificationLine.QuantityToProduce;

//Compute QuantityToProduce for others 
foreach (Recipe FT in listeFT)
        { 
            foreach (RecipeLine item in FT.Ingredients)
            {
                item.Product.QuantityToProduce += FT.ResultProduct.Quantity* item.Proportion;
            }
        }

但是在这里,让我们猜测我有 2 个食谱,其中一个使用另一个: 例如: FinishedChicken (95% 咸鸡, 5% 秘方) 咸鸡(95% 的鸡肉,5% 的盐)。 假设我计划 10 公斤 FinishedChicken: 如果在 foreach 语句中,SaltedChicken 先出现,它会将鸡肉的 QuantitytoProduce 固定为 0,而应该是 10*0.95*0.95。

我希望我已经清楚了,如果没有,请问。 你有什么主意吗? 谢谢

【问题讨论】:

  • 那么你的问题出在最后一个 foreach 上吗?
  • 如果没有看到实际的类,就很难理解所有这些抽象。我猜你需要的是装饰器模式。
  • @singsuyash 类非常简单,Planification & PlanificationLine/ Recipe & RecipeLine/ 产品数量和时间。把它们写下来会有帮助吗?

标签: c# collections foreach


【解决方案1】:

你不想迭代一个集合没有顺序,你想迭代一个集合的顺序是你永远不会遇到Recipe,除非它的所有成分都已经遇到过。

制定这样的顺序会非常复杂,我认为最好避免这种方法。

我不会尝试编写 C# 代码,因为我对 C# 语言不是很熟悉,但我认为您需要两个类,PrimitiveIngredient 和 Recipe。您需要一种方法,该方法采用Recipe 并生成PrimitiveIngredients 及其数量的列表。如果item 本身是Recipe(而不是PrimitiveIngredient),您可以通过迭代Recipe 的项目并递归调用该方法来编写此代码。

【讨论】:

  • 我正在尝试。我明白了你的观点,只是需要一些时间来尝试与规划建立联系。谢谢你的回答,我会回来告诉它是否有效
  • 它工作正常,非常感谢递归的想法!我将发布最终代码作为答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 2013-06-18
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多