指数超出范围。必须是非负数且小于List <string> </string>中集合的大小

时间:2013-09-30 11:14:25

标签: c# string list indexoutofboundsexception

我正在使用List对象来存储用户属性。

我的代码是:

 string department=string.Empty;
 List<string> otherDepartments = new List<string>();
 int no;
 string result = string.Empty;

 string queryText = string.Empty;
 using (SPSite siteCollection = SPContext.Current.Site)
 {
     using(SPWeb site = siteCollection.OpenWeb())
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
              SPUser spUser = site.CurrentUser;                        
              SPServiceContext context = SPServiceContext.GetContext(siteCollection);
              UserProfileManager upm = new UserProfileManager(context);
              UserProfile profile = upm.GetUserProfile(spUser.LoginName);
              department = profile["oiplbDepartment"].Value.ToString();

              UserProfileValueCollection otherDept = profile["oiplbOtherDepartments"];

              if (otherDept.Count != 0)
              {                           
                  foreach (var prop in otherDept)
                  {
                      otherDepartments.Add(prop.ToString());
                  }
               }
               Label1.Text = department + " Ohter Departments " + otherDepartments;
          });

          SPList list = site.Lists["Events"];
          SPListItemCollection itemColl;
          SPQuery query = new SPQuery();
          no = 1 + otherDepartments.Count;
          for (int i = 1; i <= no; i++)
          {
              if (no == 1)
              {
                  result = "<or> <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>"+department+"</Value></Eq>"+"</or>";
                  break;
              }
              else if (i == 2)
              {
                   result = "<or> <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + department + "</Value></Eq>" + 
                   "<Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + otherDepartments[i-1] + "</Value></Eq>";
              }
              else if(i >= 3)
              {
                  result = generateOr(result,otherDepartments[i-1]);
              }
         }                                  
         queryText = "<where>"+result +"</Where>";
         query.Query = queryText;
         itemColl = list.GetItems(query);
         Grid.DataSource = itemColl.GetDataTable();
         Grid.DataBind();
    }
}

public static string generateOr(string temp, string value)
{
    string r = "<or>" + temp + " <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + value + "</Value></Eq> </or>";
    return r;
}

运行程序时出现上述错误。

当且仅当属性可用时才插入值。否则不会。

但为什么我会收到错误?

1 个答案:

答案 0 :(得分:4)

因为

no = 1 + otherDepartments.Count;

将其更改为

no = otherDepartments.Count;

即使您在访问列表中的项目之前从i中减去1,您的for-loop也会循环到i == no。因此,您也可以将i <= no更改为i < no

for (int i = 1; i < no; i++)