如何在c#中解决此循环?

时间:2015-05-29 13:49:42

标签: c#-4.0

我正在使用visual studio 2010在c#桌面应用程序中工作。 我想阅读每条记录并为每个美国州加载“街道名称字典”。 例如,我读取了第一条记录(id = 1),所以我加载了AlabamaDictionary.txt,因为这条记录来自Alabama State,加载后,启动另一个进程,如地址标准化等。当这个过程结束时,我读了下一条记录(id = 2)我要检查“State”是否相同,如果状态与之前相同,我不需要再次加载AlabamaDictionary.txt,因为它已加载它,启动另一个进程像地址标准化。当这个过程结束时,我读到了来自“Arizona”的下一个记录(id = 3)。这里状态改变所以我需要加载Arizona.txt并再次启动另一个地址标准化过程等... 我的问题是改变字典,检查它何时改变。

Records
    "id" | "address"       | "state"
    1    |100 Elm St       | Alabama
    2    |300 Trawick St   | Alabama
    3    |50023 N 51st Ave | Arizona

我有下一个循环 码: DataTable记录;

for (int i = 0; i < records.Rows.Count; i++)
{
string address = records.Rows[i][1].ToString(); 
string  state = records.Rows[i][2].ToString();
streetDictionary = state + ".txt";
if(File.Exists(streetDictionary))
{
//Here I need to identify state change, 
//so if state change , to use another dictionary and load it, 
//but if don't change it (state), I need to use the same dictionary 
//(if is load it yet)
 LoadStreetDictionary(streetDictionary);

//Process Address Standardization
StreetNameStandardization(address)
}
} 

拜托,我该怎么做这个循环? 非常感谢你!

3 个答案:

答案 0 :(得分:3)

在循环之前定义一个变量......

string lastState="";

然后在检查中附上字典的读数,看看你是否仍处于同一状态

if (!state.equals(lastState))
{
    // read the dictionary here

    // then...
    lastState = state;
}
// check your address here
StreetAddressStandardization();

答案 1 :(得分:2)

您可以将最新状态存储在变量中,并在每次迭代时添加检查

string prevState = string.Empty;
   for (int i = 0; i < records.Rows.Count; i++)
    {

        string address = records.Rows[i][1].ToString(); 
        string  state = records.Rows[i][2].ToString();

    if (!state.Equals(prevSate))
    {
        streetDictionary = state + ".txt";
        if(File.Exists(streetDictionary))
        {
            //Here I need to identify state change, 
            //so if state change , to use another dictionary and load it, 
            //but if don't change it (state), I need to use the same dictionary 
            //(if is load it yet)
            LoadStreetDictionary(streetDictionary);
        }


     }

     //Process Address Standardization
     StreetNameStandardization(address)
     prevState = state; //Assigned to latest value
    } 

编辑:始终执行标准化功能。

答案 2 :(得分:2)

我希望我能正确理解你的要求。

String lastState = "";
for (int i = 0; i < records.Rows.Count; i++)
{
    string address = records.Rows[i][1].ToString(); 
    string  state = records.Rows[i][2].ToString();
    streetDictionary = state + ".txt";
    if(File.Exists(streetDictionary))
    {
        if (currentState != state)
            LoadStreetDictionary(streetDictionary);
        lastState = state;

        //Process Address Standardization
        StreetNameStandardization(address)
    }
}