0

estoy aprendiendo C# y desarrollando habilidades como autodidacta, agradezco de antemano.

Por favor pueden decirme que tengo mal en mi código para la secuencia Fibonacci:


var fibonacciNumbers = new List<int> {1, 1};

foreach(var item1 in fibonacciNumbers)
{
    if(fibonacciNumbers.Count < 20)
    {

        var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
        var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];

        fibonacciNumbers.Add(previous + previous2);
    }
    else
    {
        foreach(var item in fibonacciNumbers)
        {
            Console.WriteLine(item);
        }
    }
}

El error que muestra es:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.Collections.Generic.List1+Enumerator[T].MoveNextRare () <0x2707350 + 0x0001c> in <4c2591e5b92b41cc92fe13502e8be80a>:0 at System.Collections.Generic.List1+Enumerator[T].MoveNext () <0x2706d00 + 0x0006e> in <4c2591e5b92b41cc92fe13502e8be80a>:0 at C.Main () <0x2f48df8 + 0x00118> in <22edcb2fde3742c992b33c05f01a552d>:0 at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) <0x22c19b8 + 0x000e2> in <4c2591e5b92b41cc92fe13502e8be80a>:0 --- End of inner exception stack trace --- at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) <0x22c19b8 + 0x0010e> in <4c2591e5b92b41cc92fe13502e8be80a>:0 at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) <0x22bf048 + 0x00022> in <4c2591e5b92b41cc92fe13502e8be80a>:0 at System.CommandLine.Invocation.ModelBindingCommandHandler.InvokeAsync (System.CommandLine.Invocation.InvocationContext context) <0x2ba70f8 + 0x000ca> in <2915f7cee4c54568a16c327bb196b74e>:0 at System.CommandLine.Invocation.InvocationPipeline+<>c__DisplayClass2_0.b__0 (System.CommandLine.Invocation.InvocationContext invocationContext, System.Func`2[T,TResult] next) <0x2ba6600 + 0x0011e> in <2915f7cee4c54568a16c327bb196b74e>:0 at System.CommandLine.Invocation.InvocationPipeline.InvokeAsync (System.CommandLine.IConsole console) <0x2b943d8 + 0x001a6> in <2915f7cee4c54568a16c327bb196b74e>:0 at System.CommandLine.Invocation.InvocationExtensions.InvokeAsync (System.CommandLine.Parser parser, System.CommandLine.ParseResult parseResult, System.CommandLine.IConsole console) <0x2b903b0 + 0x000c4> in <2915f7cee4c54568a16c327bb196b74e>:0 at System.CommandLine.Invocation.InvocationExtensions.InvokeAsync (System.CommandLine.Parser parser, System.String[] args, System.CommandLine.IConsole console) <0x2b2ddc8 + 0x000d6> in <2915f7cee4c54568a16c327bb196b74e>:0 at MLS.WasmCodeRunner.CodeRunner.ExecuteRunRequest (MLS.WasmCodeRunner.WasmCodeRunnerRequest runRequest, System.Int32 sequence) <0x2a69198 + 0x00112> in <62ee9ae2d85448949e3cc7803ea8d2c2>:0

1 respuesta 1

4

El problema que tienes es que estás recorriendo la lista de los números fibonacciNumbers a la vez que le vas añadiendo valores a la lista, cosa que no se puede hacer como te indica el error que nos muestras:

System.InvalidOperationException: Collection was modified;

Deberías hacer otro tipo de bucle, sin recorrer la lista para ir añadiendole números a esa lista sin que te salte el error al intentar recorrer la misma.

Te pongo un ejemplo de cómo podrías hacerlo:

var fibonacciNumbers = new List<int> { 1, 1 };

for (int i = 0; i < 20; i++)
{
    var previous = fibonacciNumbers[i + 1];
    var previous2 = fibonacciNumbers[i];

    fibonacciNumbers.Add(previous + previous2);
}

foreach (var item in fibonacciNumbers)
{
    Console.WriteLine(item);
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.