I have the following piece of code that is giving me problems and I would appreciate any help:
private static string CreateOptionString(List<VehicleOption> Options)
{
StringBuilder returnValue = new StringBuilder();
foreach (VehicleOption option in Options)
{
if (option.OptionStatus == ExtendedResponse.OptionState.Included)
{
if (returnValue.Length > 0)
{
returnValue.Append(", ");
}
returnValue.Append(option.OptionName);
}
}
return returnValue.ToString();
}
My original problem was that I was getting a System.InvalidOperationException: collection was modified error on my foreach loop.
1)I still can't figure out why I would get this error because I don't see anywhere that it is modified.
Someone suggested that I copy the List to a new List and loop through the new List. I did that and it got rid of the InvalidOperationException. However, I tried coping the list 2 different ways and both gave me a System.ArgumentException: Destination array was not long enough. Here are the two ways I tried to copy the list
List<VehicleOption> newOptions = new List<VehicleOption>(Options);
and
List<VehicleOption> newOptions = new List<VehicleOption>();
newOptions.AddRange(Options);
Both of these gave me a System.ArgumentException: Destination array was not long enough.
2)Why would either of these methods give me that exception?
Any help would be appreciated, because I am stumped.
Thanks!
Optionsis modified from another thread during theforeach.