逻辑错误:“ bsList()”列表意外更改大小

时间:2019-02-14 12:26:38

标签: c#

我将队列复制到列表“ var bsList = bs.ToList();”逐步执行代码,我发现bsList从47个JSON元素更改为37个。我不知道这是怎么可能的。当我到达这一行时,“ var listBuy = bsList;”在下面的代码中,它具有较少的元素。这怎么可能?

                // bs queue to list
            var bsList = bs.ToList();

            //get all sell objects in a list
             var listSell = bsList; // **bsList has 47 JSON elements**
            listSell.RemoveAll(s => s.BuySell == "Buy");

            // make the latest sell date object
            DateCloseBuySell lastSell = new DateCloseBuySell();
            lastSell = listSell.Aggregate((i1, i2) => i1.Date > i2.Date ? i1 : i2);

            // remove lastSell object from ListSell
            listSell.RemoveAll(s => s.Date == lastSell.Date);

            // get the new latest sell date object
            DateCloseBuySell lastSell2 = new DateCloseBuySell();
            lastSell2 = listSell.Aggregate((i1, i2) => i1.Date > i2.Date ? i1 : i2);

            // get the buy objects in a list
            var listBuy = bsList; // **shows only 37 elements in bsList**
            listBuy.RemoveAll(s => s.BuySell == "Sell");

1 个答案:

答案 0 :(得分:3)

之所以发生,是因为您正在分配对其他变量的引用并对其执行操作。

        var listSell = bsList; // **bsList has 47 JSON elements**
        listSell.RemoveAll(s => s.BuySell == "Buy");

这里listSell引用bsList元素,然后更新listSell。

如果您不希望出现这种情况,则应执行以下列表的副本

   List<Int32> copy = original.ToList(); //shallow copy