-1

I'm trying to use yield to return string on each iteration, but instead of a string, my res has type {Namespace.Class.<getMutations>d__10}. I get all the results I want, but they are returned all at once and not one by one. What am I doing wrong?

public static IEnumerable<string> generate(string mask)
{
     foreach (List<string> pattern in list)
     {
         var res = getMutations(pattern);
         yield return "result:  " + res;
     }
}

private static IEnumerable<string> getMutations(List<string> pattern)
{
    IEnumerable<string> mutations = null;
    switch (pattern.Count)
    {               
        case 4:
            mutations =
            from m0 in pattern[0]
            from m1 in pattern[1]
            from m2 in pattern[2]
            from m3 in pattern[3]
            select "" + m0 + m1 + m2 + m3;
            break;
        case 5:
            mutations =
            from m0 in pattern[0]
            from m1 in pattern[1]
            from m2 in pattern[2]
            from m3 in pattern[3]
            from m4 in pattern[4]
            select "" + m0 + m1 + m2 + m3 + m4;
            break;
    }

    foreach (var mutation in mutations)
        yield return mutation;
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
MeeraWeeks
  • 83
  • 9

2 Answers2

1

I would have liked to answer you this question, but I found a better and complete answer to your question that you can find in the link below.

What is the yield keyword used for in C#?

For this you need to understand the Deferred Execution :

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/deferred-execution-example

sayah imad
  • 1,507
  • 3
  • 16
  • 24
0

In each iteration you are returning the result of getMutations and that is an enumerable. If you want to return strings you have to iterate over the result of getMutations and yield those strings.

idstam
  • 2,848
  • 1
  • 21
  • 30
  • But inside getMutations I have loop which iterates through all strings, and returns them (or, at least should) one by one – MeeraWeeks Mar 02 '20 at 10:11
  • 1
    You can't return things one by one in .NET without returning a collection, so basically, you're returning a collection. The `yield return` is just syntactic sugar and some helpful code rewriting by the compiler to make it easier to write this "return a collection" type of thing. But you are returning a collection. – Lasse V. Karlsen Mar 02 '20 at 10:14