[英]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 . 在执行foreach时,我可以看到它在第一个复飞中放置了0 ,然后在第二个复飞中放置了1 。 However, during the loop it only has 1 value for GEvents each go-around.
但是,在循环过程中,每次复飞GEvent的值只有 1 。 Once it returns GEvents it only has the last inserted item in the dictionary?
返回GEvents后,它在字典中只有最后插入的项目吗?
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.