I'm working with various lists and types under memory constraints and would like to free up memory while iterating through a list, so I've set up a generic example:
public class Test
{
List<PersonClass> personList = new(450000);
public Test()
{
for(int i = 0; i < 450000; i++)
{
personList.Add(new PersonClass());
}
}
public List<InfoClass> GetUpdatedList(List<PersonClass> personList)
{
List<InfoClass> secondList = new();
for(int i=personList.Count - 1; i > -1; i--)
{
var aPerson = personList[i];
secondList.Add(new InfoClass()
{
FirstName = aPerson.FirstName,
LastName = aPerson.LastName
});
personList.RemoveAt(i);
}
return secondList;
}
public class PersonClass
{
public string FirstName { get; set; } = "Something Random";
public string LastName { get; set; } = "Something Else Random";
}
public class InfoClass
{
public string FirstName { get; set; } = "Something Random";
public string LastName { get; set; } = "Something Else Random";
public string StateName { get; set; } = "Something Random";
public string CityName { get; set; } = "Something Else Random";
}
}
How can I free up memory while removing elements before reaching the end of the loop?