Se usi l'oggetto SPQuery di SharePoint 2007 in un ciclo e costruisci l'oggetto fuori dal ciclo (vedi commento //wrong) hai degli strani comportamenti.

In pratica tutto funziona se la query restituisce dei dati. Nel caso in cui la query non ritorna dati, stranamente vengono restituiti gli stessi dati della query precedente anziché niente. In pratica non si riesce a discriminare se la query ha restituito dei dati corretti.

Per risolvere il problema è sufficiente creare l'oggetto SPQuery all'interno del ciclo (vedi commento //OK).
C#
public class Valore
    {
        public string Key { get; set; }
        public int Quantita { get; set; }
    }

    //start: A=1, C=3
    //wrong: A=1, C=19
    //ok: A=7, B=23, C=14, D=19
static void Main(string[] args)
{
  List<Valore> dati = new List<Valore> {
                    new Valore { Key ="C", Quantita= 14}
                    ,new Valore {Key="B",Quantita= 23}
                    ,new Valore {Key="A",Quantita= 7}
                    ,new Valore {Key="D",Quantita= 19}
                };

  string url = "http://intranet.contoso.com";
  using (SPSite site = new SPSite(url))
  {
    using (SPWeb web = site.OpenWeb())
    {
      SPList list = web.Lists["Test"];
      //SPQuery query = new SPQuery();  //wrong

      foreach (Valore v in dati)
      {
        SPQuery query = new SPQuery();  //OK
        query.Query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>"
            , v.Key);
        SPListItemCollection items = list.GetItems(query);
        SPListItem item = null;
        if (items.Count > 0)
        {
          item = items[0];
        }
        else
        {
          item = items.Add();
          item[SPBuiltInFieldId.Title] = v.Key;
        }
        item["Quantita"] = v.Quantita;
        item.Update();
      }
    }
  }
}
quindi questo codice è sbagliato
C#
SPQuery query = new SPQuery();  //wrong

foreach (Valore v in dati)
{
    query.Query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>"
            , v.Key);
  ...
}
mentre questo è giusto creo un nuovo aggetto ad ogni iterazione
C#
foreach (Valore v in dati)
{
   SPQuery query = new SPQuery();  //nuovo oggetto ad ogni iterazione
   query.Query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>"
            , v.Key);
  ...
}
Potrebbe interessarti anche: