我有以下代码:
public Dictionary<int, Ticket> GetNewTickets()
{
Dictionary<int, Ticket> output = new Dictionary<int, Ticket>();
foreach (KeyValuePair<int, Ticket> item in ticketStore)
{
if (!ticketStoreNew.ContainsKey(item.Key))
{
output.Add(item.Key, item.Value);
}
}
ticketStoreNew = ticketStore;
return output;
}`
需要字典ticketStore
检查它是否在ticketstorenew中没有任何新元素,并将它们放入输出字典中。然后,Ticketstorenew设置为Ticket Store,直到使用另一种方法更新Ticket Store,并且此方法再次运行。
但是,当我包含ticketStoreNew = ticketStore
行时,程序将返回一个空词典。看来该方法没有顺序执行,并且在for循环之前运行。
我真的只需要返回添加到ticketStore
字典中的任何新项目。
编辑以下是获取ticketStore
的代码:
public void UpdateTickets(string inputXml)
{
// If no new tickets exit
if (inputXml.Trim() == "") { return; }
//xmlString = inputXml;
// Load XML into an enumerable
XElement xelement = XElement.Parse(inputXml);
IEnumerable<XElement> xml = xelement.Elements();
foreach (var item in xml)
{
if (item.Name == "incident")
{
int id;
// If ID can be converted to INT
if (Int32.TryParse(item.Element("id").Value, out id))
{
// If ticket is not already in store create ticket and populate data
if (!ticketStore.ContainsKey(id))
{
Ticket ticket = new Ticket();
ticket.id = id;
ticket.number = Int32.Parse(item.Element("number").Value);
ticket.title = item.Element("name").Value;
ticket.description = item.Element("description").Value;
ticketStore.Add(id, ticket);
}
}
}
}
}
}
门票都是基于从samanage api获取XML的
如果其他方法更新票务store,则分配是问题。它没有将售票员的内容复制到Ticketstorenew,它将参考票证固定器设置为与Ticketstore指向同一实例。因此它们是相同的对象,并且始终具有相同的内容。尝试创建一个新词典来复制项目:
ticketStoreNew = new Dictionary<int, Ticket>(ticketStore);
尝试以下代码:
private Dictionary<int, Ticket> ticketStoreNew =
new Dictionary<int, Ticket>(); // add this line
public Dictionary<int, Ticket> GetNewTickets()
{
Dictionary<int, Ticket> output = new Dictionary<int, Ticket>();
foreach (KeyValuePair<int, Ticket> item in ticketStore)
{
if (!ticketStoreNew.ContainsKey(item.Key))
{
output.Add(item.Key, item.Value);
ticketStoreNew.Add(item.Key, item.Value); // add this line
}
}
//ticketStoreNew = ticketStore; remove this line
return output;
}