In my application, I have the notion of recipes and each recipe has ingredients which can be replaced by another ingredient. What I want to do is to generate every possibility with each ingredient. I have the following structure as CLR objects:
public class Food
{
public Food()
{
NutritionalValues = new Collection<FoodNutritionalValue>();
}
public string Name { get; set; }
public string Category { get; set; }
public ICollection<FoodNutritionalValue> NutritionalValues { get; set; }
}
public class FoodNutritionalValue
{
public string Type { get; set; }
public decimal Value { get; set; }
}
public class Recipe
{
public Recipe()
{
IngredientGroups = new Collection<IngredientGroup>();
}
public string Name { get; set; }
public ICollection<IngredientGroup> IngredientGroups { get; set; }
}
public class IngredientGroup
{
public IngredientGroup()
{
Ingredients = new Collection<Food>();
}
public ICollection<Food> Ingredients { get; set; }
}
IngredientGroup
is something that can be replaced by each other. So, for a recipe, there needs to be one ingredient from each of the IngredientGroup
s. However, as I don't know the number of IngredientGroup
s, I'm unable to iterate through them to find out each possibility.
For example, the following code works fine if I were to know the count of the IngredientGroups.Count
beforehand:
Recipe recipe2 = new Recipe();
IngredientGroup ingredientGroup3 = new IngredientGroup();
IngredientGroup ingredientGroup4 = new IngredientGroup();
IngredientGroup ingredientGroup5 = new IngredientGroup();
recipe2.Name = "Recipe2";
ingredientGroup3.Ingredients.Add(new Food { Name = "Food8", Category = "Categor8" });
ingredientGroup3.Ingredients.Add(new Food { Name = "Food9", Category = "Categor9" });
ingredientGroup4.Ingredients.Add(new Food { Name = "Food5", Category = "Categor5" });
ingredientGroup4.Ingredients.Add(new Food { Name = "Food10", Category = "Categor10" });
ingredientGroup4.Ingredients.Add(new Food { Name = "Food11", Category = "Category11" });
ingredientGroup5.Ingredients.Add(new Food { Name = "Food3", Category = "Categor3" });
ingredientGroup5.Ingredients.Add(new Food { Name = "Food4", Category = "Categor4" });
recipe2.IngredientGroups.Add(ingredientGroup3);
recipe2.IngredientGroups.Add(ingredientGroup4);
recipe2.IngredientGroups.Add(ingredientGroup5);
var recipes = new[] { recipe2 };
List<string> results = new List<string>();
foreach (var rcp in recipes)
{
var group1 = rcp.IngredientGroups.ElementAt(0);
var group2 = rcp.IngredientGroups.ElementAt(1);
var group3 = rcp.IngredientGroups.ElementAt(2);
foreach (var item1 in group1.Ingredients)
foreach (var item2 in group2.Ingredients)
foreach (var item3 in group3.Ingredients)
{
results.Add(string.Format("{0}, {1}, {2}", item1.Name, item2.Name, item3.Name));
}
}
I'm sure I am missing something here. How I can generate every possibility at runtime?