【发布时间】:2020-06-28 00:59:46
【问题描述】:
我有以下仅执行第一个 foreach 循环的代码。当我在 Visual Studio 中进入逐步模式时,程序只会跳过每个后续的 foreach 循环。为什么会发生这种情况,是否有解决方法?有没有办法在不使用 foreach 循环的情况下循环通过 IEnumerable(比如 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);
}
【问题讨论】: