Foreach循环迭代计数不正确

时间:2016-03-02 10:15:08

标签: c# list foreach iteration

我有一个有38条记录的IList,当我使用foreachloop迭代它时,它只迭代两次。我无法弄清楚为什么会这样!

foreach (UserRecord rec in userlist)
{
    dictionary.Add(rec.Login, rec.Group);
}

任何想法都会有很大的帮助。

3 个答案:

答案 0 :(得分:1)

最可能的原因,恕我直言,抛出异常。让我们修改您的解决方案(仅用于测试目的)和 debug

foreach (UserRecord rec in userlist) {
  if (null == rec) 
    MessageBox.Show("rec is null!");              // <- put a break point here
  else if (null == rec.Login)
    MessageBox.Show("rec.Login is null!");        // <- here
  else if (dictionary.ContainsKey(rec.Login))
    MessageBox.Show("rec.Login already exists!"); // <- and here 
  else
    dictionary.Add(rec.Login, rec.Group);
}

答案 1 :(得分:0)

当您添加到字典中时,我的猜测是抛出异常。

请改为尝试:

int Count = 0;

foreach (UserRecord rec in userlist)
{
    try
    { 
        dictionary.Add(rec.Login, rec.Group); 

    } 
    catch//(Exception ex)
    {
        //Console.WriteLine("Exception: " + ex.Message + "\nStackTrace: " + ex.Stacktrace);
    }
    finally
    {
        Count++;

    }

}

MessageBox.Show("Number of iterations = " + Count);

答案 2 :(得分:0)

for(int i = 0 ; i < userlist.Count ; i++)
{
   try
   {
       dictionary.Add(userlist[i].Login, userlist[i].Group);
   }
   catch(Exception ex)
   {
      //check here witch userlist is throwing exception
   }
}
  • for better understanding of your problems always write try catch in your code.