Exiting in foreach or GetEnumerator ()?

Which is preferable in this case:

IEnumerator<Cat> EnumerateCats()
{
    var rawCats = GetRawCats();

    foreach(var cat in rawCats)
    {
        var typedCat = new Cat
        {  
            Name = cat.Key;
            Breed = cat.Value;
        };

        yield return typedCat;
    }
}

or

IEnumerator<Cat> EnumerateCats()
{
    return GetRawCats()
       .Select(cat => new Cat
        {  
            Name = cat.Key;
            Breed = cat.Value;
        })
       .GetEnumerator();
}

I prefer the last code sample. Does it work the same as the first?

+4
source share
3 answers

I am not sure why you need to return IEnumerator<Cat>. I would just change it to return IEnumerable<Cat>, so you can simply write:

IEnumerable<Cat> EnumerateCats()
    => GetRawCats()
       .Select(cat => new Cat
        {  
            Name = cat.Key;
            Breed = cat.Value;
        });
+5
source

You can see the difference in writing your method with yieldand without it in this example

static void Main(string[] args)
{
    foreach (int i in List())
    {
        Console.WriteLine($"In List foreach {i}");
    }
    Console.WriteLine("*****");
    foreach (int i in Yield())
    {
        Console.WriteLine($"In Yeild foreach {i}");
    }
}

private static IEnumerable<int> List()
{
    var inputList = new List <int> { 1, 2, 3 };
    List<int> outputlist = new List<int>();
    foreach (var i in inputList)
    {
        Console.WriteLine($"In List Method {i}");
        outputlist.Add(i);
    }
        return outputlist.AsEnumerable();
}

private static IEnumerable<int> Yield()
{
    var inputList = new List<int> { 1, 2, 3 };
    foreach (var i in inputList)
    {
        Console.WriteLine($"In Yield Method {i}");
        yield return i;
    }
}

Here is the result:

In List Method 1
In List Method 2
In List Method 3
In List foreach 1
In List foreach 2
In List foreach 3
*****
In Yield Method 1
In Yield foreach 1
In Yield Method 2
In Yield foreach 3
In Yield Method 3
In Yield foreach 3
0
source

yield , , yield. , .

-1

All Articles