我有以下代码仅执行第一个foreach循环。当我进入Visual Studio的分步模式时,该程序将跳过每个后续的foreach循环。为什么会发生这种情况,并且有解决方法?有没有一种方法可以循环使用IEnumerable <>而不使用foreach循环(就像for循环一样,尽管我还没有弄清楚该怎么做)。
using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
...
public class State
{
public int Id { get; set; }
public string Name { get; set; }
public int Pop { get; set; }
public string Ab { get; set; }
public int Reps { get; set; }
public double standardQuota { get; set; }
public int lowerQuota { get; set; }
public int upperQuota { get; set; }
}
...
static void currentRule(int num)
{
IEnumerable<State> records = null;
int size = 0;
Console.WriteLine("Please enter a size for the house, greater than the number of states. Current is 435. select 1 for wyoming rule or 2 for cube root.");
string s = Console.ReadLine();
size = Int32.Parse(s);
if (num == 1)
{
string path = "C:/.../pop50.csv";
using (var reader = new StreamReader(path))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
records = csv.GetRecords<State>();
int total = 0;
foreach (var state in records)
{
total += state.Pop;
}
var standardDivisor = total / size;
foreach (var state in records)
{
state.standardQuota = state.Pop / standardDivisor;
state.lowerQuota = (int)Math.Floor(state.standardQuota);
state.upperQuota = (int)Math.Ceiling(state.standardQuota);
state.Reps = 1;
size -= 1;
}
while (size > 0)
{
double max = 0;
double maxIndex = 0;
int i = -1;
foreach (var state in records)
{
i++;
var numSeats = state.Reps;
var div = state.Pop / Math.Sqrt(size * (size + 1));
if (div > max)
{
max = div;
maxIndex = i;
}
}
foreach (var state in records)
{
if (state.Id == maxIndex)
{
state.Reps++;
size--;
}
}
}
}
}
print(records);
}
GetRecords
返回有状态IEnumerable
的收益率,当时产生单个记录。这里的有效词是有状态的-一旦您消耗了一条记录(例如,通过循环遍历它foreach
),它就消失了。
您可以在这里采取几种方法:
foreach
循环中,而不是执行逻辑不同部分的三个不同循环中。GetRecords
每次需要遍历记录时调用一次。请注意,这将重新读取文件,因此您将执行三倍的I / O。List
(例如,通过使用Linq ToList()
),然后在需要时对其进行迭代。请注意,这意味着您将整个文件的内容保留在其中的一小部分。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句