C# 如何设计在编译时以未知顺序遍历多个列表的算法?
我正在创建一个程序,它根据用户定义的设置处理数据。 在处理过程中,我有一些相关的列表,必须根据这些用户定义的设置进行迭代;用户决定这些列表的迭代顺序 我想知道如何设计一种算法来迭代这些列表,同时仍然有非常可维护的代码。这里的想法不是以一个函数结束,该函数有一个巨大的切换案例,其中每个案例都对一个列表进行迭代 示例:C# 如何设计在编译时以未知顺序遍历多个列表的算法?,c#,algorithm,loops,code-maintainability,C#,Algorithm,Loops,Code Maintainability,我正在创建一个程序,它根据用户定义的设置处理数据。 在处理过程中,我有一些相关的列表,必须根据这些用户定义的设置进行迭代;用户决定这些列表的迭代顺序 我想知道如何设计一种算法来迭代这些列表,同时仍然有非常可维护的代码。这里的想法不是以一个函数结束,该函数有一个巨大的切换案例,其中每个案例都对一个列表进行迭代 示例: 假设我需要处理的数据是不同类型食物的列表。 用户必须指定不同食物组的加工顺序。食品组只是存储各种食品的列表: List<string> grains = new List
假设我需要处理的数据是不同类型食物的列表。 用户必须指定不同食物组的加工顺序。食品组只是存储各种食品的列表:
List<string> grains = new List<string> { "Bread", "Pasta", "Cereal", "Rice" };
List<string> vegetables = new List<string> { "Corn", "Pea", "Carrot", "Tomato" };
List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Pear" };
List<string> meat = new List<string> { "Beef", "Chicken", "Pork", "Turkey" };
List<string> diary = new List<string> { "Milk", "Cheese", "Yogurt", "Cream" };
在我的应用程序中,case语句实际上包含的代码比示例中简单的foreach循环多得多。有没有更好的方法来设计这个算法?虽然没有必要,但我想知道是否也有一种可扩展的方法来设计这样的算法(添加/删除新食物组不会破坏算法)。将其作为字典:
Dictionary<string, List<string>> lists = new Dictionary<string, List<string>>();
lists["grains"] = new List<string> { "Bread", "Pasta", "Cereal", "Rice" };
lists["vegetables"] = new List<string> { "Corn", "Pea", "Carrot", "Tomato" };
lists["fruits"] = new List<string> { "Apple", "Orange", "Banana", "Pear" };
lists["meat"] = new List<string> { "Beef", "Chicken", "Pork", "Turkey" };
lists["diary"] = new List<string> { "Milk", "Cheese", "Yogurt", "Cream" };
实际上,C#中还有一些更好的语法用于初始化。请参阅:描述您要查找的代码的术语是“数据驱动”。
foreach(string foodGroup in order)
{
switch(foodGroup)
{
case "grains":
foreach(string foodItem in grains)
{
ProcessFood(foodItem);
}
break;
case "vegetables":
foreach(string foodItem in vegetables)
{
ProcessFood(foodItem);
}
break;
case "fruits":
foreach(string foodItem in fruits)
{
ProcessFood(foodItem);
}
break;
case "meat":
foreach(string foodItem in meat)
{
ProcessFood(foodItem);
}
break;
case "diary":
foreach(string foodItem in diary)
{
ProcessFood(foodItem);
}
break;
}
}
Dictionary<string, List<string>> lists = new Dictionary<string, List<string>>();
lists["grains"] = new List<string> { "Bread", "Pasta", "Cereal", "Rice" };
lists["vegetables"] = new List<string> { "Corn", "Pea", "Carrot", "Tomato" };
lists["fruits"] = new List<string> { "Apple", "Orange", "Banana", "Pear" };
lists["meat"] = new List<string> { "Beef", "Chicken", "Pork", "Turkey" };
lists["diary"] = new List<string> { "Milk", "Cheese", "Yogurt", "Cream" };
foreach(string foodGroup in order)
{
foreach(string foodItem in lists[foodGroup])
{
ProcessFood(foodItem);
}
}