Home > Net >  Why a method is modifying a List<string> variable in my Load Page?
Why a method is modifying a List<string> variable in my Load Page?

Time:10-29

I want to create two List with methods, the first method create a new list, and the second modify the first one but return a new one. For example, the first list has 200 items, and after add and delete some items in the second method, the returned one has 120 items. But the second method is actually modifying the first list (now both list has 120 items). What am I doing wrong?. PD. I'm learning

protected void Page_Load(object sender, EventArgs e)
{
    List<string> firstList = OEEClass.GetCompleteListDocument(DateTime.Today, "BZX"); // Let say it has 200 items
    List<string> modifiedList = OEEClass.ModifyList(firstList); // The returned list has less items
}

public class OEEClass
{
    public static List<string> GetCompleteListDocument(DateTime Fecha, string noMaquina)
    {            
        var rawDoc = new HtmlDocument();
        var tempList = new List<string>();

        string url = @"C:/www/WPCS-Feedback/"   Fecha.Year   "/"   Fecha.Month   "/"   Fecha.Day.ToString("d2")   "/"   "Production state data.htm";

        if (File.Exists(url) == true)
        {
            rawDoc.Load(url);

            string cleanString = rawDoc.DocumentNode.InnerText.Trim().Replace(" ", "");
            cleanString = Regex.Replace(cleanString, @"^\s $[\r\n]*", string.Empty, RegexOptions.Multiline);

            tempList = Regex.Split(cleanString, "\r\n|\r|\n").ToList();
            tempList.RemoveRange(0, 5);

            for (int j = 0; j < tempList.Count; j  )
            {
                if (tempList[j].StartsWith("ProductionTerminated") || tempList[j].StartsWith("ProductionInterrumpted"))
                {
                    tempList.Insert(j   4, "PressSingleCycleActivated=0");
                }

            }

        }

        return tempList;
    }

    public static List<string> ModifyList(List<string> completeListDocument)
    {        
        for (int i = 0; i < completeListDocument.Count; i  )
        {
            if (completeListDocument[i].StartsWith("MachineSetup"))
            {
                completeListDocument.RemoveRange(i, 6);
                i--;
            }

        }
        return completeListDocument;
    }
}

CodePudding user response:

The simplest thing you can do is make a copy of your list before modifying it:

public static List<string> ModifyList(List<string> completeListDocument)
{
    var results = new List<string>(completeListDocument);
    for (int i = 0; i < results.Count; i  )
    {
        if (results[i].StartsWith("MachineSetup"))
        {
            results.RemoveRange(i, 6);
            i--;
        }
    }
    return results;
}
  • Related