IEnumerable <T> - How to use one method for both counters

This is probably a stupid question, but I haven't found an answer to it anywhere.

I have a simple class that implements IEnumerable<KeyValuePair<int, Line>>

. It is a base class for a file reader that reads EFT flat files from a bank.

Derived classes implement the abstract method GetNext

you see in your code and return a line based type depending on the type of string they are reading. I originally had callers called GetNext

in a loop before EOF when they return zero. With a counter, they can call foreach instead and loop through the reader.

But why do I need to implement two counters? Both do the same. And I cannot refactor it to call the same method with right click => Refactor => Extract Method because the method contains a statement . But of course I can use one helper method for both? What would be the signature of such a method? yield

using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace EasyDebit.BankInterface
{
    public abstract class FileReader : IEnumerable<KeyValuePair<int, Line>>
    {
        protected int current;
        protected List<string> lines = new List<string>();
        private string filename;

        public FileReader(string filename)
        {
            this.filename = filename;
            this.lines = File.ReadAllLines(filename).ToList();
        }

        public string Filename
        {
            get { return filename; }
        }

        public IEnumerator<KeyValuePair<int, Line>> GetEnumerator()
        {
            Line line = null;
            current = 0;

            while ((line = GetNext()) != null)
                yield return new KeyValuePair<int, Line>(current, line);
        }

        public abstract Line GetNext();

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            Line line = null;
            current = 0;

            while ((line = GetNext()) != null)
                yield return new KeyValuePair<int, Line>(current, line);
        }
    }
}

      

+3


source to share


1 answer


Just drop it to eliminate duplicate code.



    public IEnumerator<KeyValuePair<int, Line>> GetEnumerator()
    {
        Line line = null;
        current = 0;

        while ((line = GetNext()) != null)
            yield return new KeyValuePair<int, Line>(current, line);
    }

    public abstract Line GetNext();

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return (IEnumerator)GetEnumerator();
    }

      

+4


source







All Articles