C#方法不是按顺序执行的

时间:2016-12-16 03:01:56

标签: c# dictionary methods compare difference

我有以下代码:

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设置为ticketStore,直到使用其他方法更新ticketStore并再次运行此方法。

但是,当我包含行ticketStoreNew = ticketStore时,程序返回一个空字典。看起来该方法没有按顺序执行,而是在for循环之前运行。

我真的只需要返回添加到ticketStore字典中的任何新项目。

EDIT 以下是获取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。

2 个答案:

答案 0 :(得分:0)

如果另一个方法更新ticketStore,那么分配就是问题所在。它不会将ticketStore的内容复制到ticketStoreNew,它会将引用ticketStoreNew设置为指向与ticketStore相同的实例。因此它们是相同的对象并且总是具有相同的内容。尝试创建一个新的词典来复制项目:

ticketStoreNew = new Dictionary<int, Ticket>(ticketStore);

答案 1 :(得分:0)

试试这段代码:

    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;
    }