简体   繁体   中英

Google Calendar API v3 loop with Dictionary saves just 1

Hey all I have the following code below that I am using in order to save each calendar event to a Dictionary.

Dictionary<int, GoogleCalEvents> GEvents;

public class GoogleCalEvents
{
    public string timeFrom { get; set; }
    public string timeTo { get; set; }
    public TimeSpan duration { get; set; }
    public string summary { get; set; }
    public string description { get; set; }
    public string status { get; set; }
    public string organizer { get; set; }
    public EventAttendee attendees { get; set; }
    public int ID { get; set; }
}

public Dictionary<int, GoogleCalEvents> getCalEvents()
{
   foreach (var eventItem in events.Items)
   {
      GEvents = new Dictionary<int, GoogleCalEvents>()
      {
           {
                loopID,
                new GoogleCalEvents {
                     timeFrom    = from,
                     timeTo      = to,
                     duration    = duration,
                     summary     = summary,
                     description = description,
                     status      = status,
                     organizer   = organizer,
                     attendees   = attendees,
                     ID          = loopID
                 }
            }
       };

       loopID++;
    }

    return GEvents;
}

And calling that class:

calendarAPI myClass = new calendarAPI();
Dictionary<int, GoogleCalEvents> blah = myClass.getCalEvents();

As its doing the foreach I can see it placing a 0 for the first go-around and then 1 for the second . However, during the loop it only has 1 value for GEvents each go-around. Once it returns GEvents it only has the last inserted item in the dictionary?

How am I setting this up incorrectly?

You are recreating the dictionary in the loop. You should do it once only

public Dictionary<int, GoogleCalEvents> getCalEvents()
{
    var loopID=0;
    var GEvents = new Dictionary<int, GoogleCalEvents>();
    foreach (var eventItem in events.Items)
    {

        GEvents.Add(loopID, new GoogleCalEvents
        {
            timeFrom = from,
            timeTo = to,
            duration = duration,
            summary = summary,
            description = description,
            status = status,
            organizer = organizer,
            attendees = attendees,
            ID = loopID
        });
    }
    loopID++;

    return GEvents;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM