嗨,我有一个关于递归算法的问题。 这段代码运行时间过长。我已经从Internet上搜索了,我计划将算法从递归改为迭代。
我很难更改代码,因为没有“返回”条件(它总是循环直到年份,类型,操作,位置,部门和职位列表完成)。
如何更改算法?
以下是代码:
DataSet dataSet = new DataSet();
var years = GetDataForReportMonthlyFTEWorkCompletionByDepartment(new string[] { string.Empty }, group);
foreach (var year in years)
{
var types = GetDataForReportMonthlyFTEWorkCompletionByDepartment(new string[] { year.Year.ToString() }, group);
foreach (var type in types)
{
var departments = GetDataForReportMonthlyFTEWorkCompletionByDepartment(new string[] { year.Year.ToString(), type.ContractorType }, group);
foreach (var department in departments)
{
var operations = GetDataForReportMonthlyFTEWorkCompletionByDepartment(new string[] { year.Year.ToString(), type.ContractorType, department.Department }, group);
foreach (var operation in operations)
{
var positions = GetDataForReportMonthlyFTEWorkCompletionByDepartment(new string[] { year.Year.ToString(), type.ContractorType, department.Department, operation.Operation }, group);
foreach (var position in positions)
{
var locations = GetDataForReportMonthlyFTEWorkCompletionByDepartment(new string[] { year.Year.ToString(), type.ContractorType, department.Department, operation.Operation, position.Position }, group);
foreach (var location in locations)
{
DataTable tbl = ReportExport.ConvertToDataTable<ReportMonthlyFTE>(
GetDataForReportMonthlyFTEWorkCompletionByDepartment(new string[] { year.Year.ToString(), type.ContractorType, department.Department, operation.Operation, position.Position, location.Location }, group).ToList());
dataSet.Tables.Add(tbl);
}
}
}
}
}
}
答案 0 :(得分:0)
我认为yield
可能会解决您的问题。这将允许您从调用代码控制枚举,以便您可以在需要时提前逃脱。
class Program
{
static void Main(string[] args)
{
foreach (var dataTable in GetData())
{
Console.WriteLine("Got more data.");
Console.WriteLine("Continue getting more data?");
ConsoleKeyInfo keyInfo = Console.ReadKey();
if (keyInfo.KeyChar != 'y')
{
// Stop enumerating.
break;
}
}
Console.ReadKey(true);
}
static IEnumerable<DataTable> GetData()
{
while (true)
{
yield return new DataTable();
}
}
}
另请注意返回类型IEnumerable<out T>
。