Override IEnumerable Where

后端 未结 2 1824
小鲜肉
小鲜肉 2021-01-24 03:24

I\'ve written a class that implements IEnumerable :

public class MyEnumerable : IEnumerable
{ 
    IEnumerator IEnumerable.GetEnumerator()
    {
         


        
2条回答
  •  野的像风
    2021-01-24 04:13

    Update

    From your comment your enumerator is a lazy file enumerator and you want to be able to select items from it based on a predicate and still have the laziness.

    You could create another class inheriting that class or an interface to help with this.

    Here is an example

    public class FileItem
    {
        //Some properties
    }
    
    public interface IFileEnumerator : IEnumerable
    {
        IFileEnumerator Where(Func predicate);
    }
    
    public class FileEnumerator : IFileEnumerator
    {
        private readonly string fileName;
    
        public FileEnumerator(string fileName)
        {
            this.fileName = fileName;
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    
        public IEnumerator GetEnumerator()
        {
            var items = new List();
    
            //Read from file and add lines to items
    
            return items.GetEnumerator();
        }
    
        public IFileEnumerator Where(Func predicate)
        {
            return new MemoryEnumerator(ToEnumerable(GetEnumerator()).Where(predicate));
        }
    
        private static IEnumerable ToEnumerable(IEnumerator enumerator) 
        {
            while (enumerator.MoveNext()) 
            {
                yield return enumerator.Current;
            }
        }
    }
    
    public class MemoryEnumerator : IFileEnumerator
    {
        private readonly IEnumerable items;
    
        public MemoryEnumerator(IEnumerable items)
        {
            this.items = items;
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    
        public IEnumerator GetEnumerator()
        {
            return items.GetEnumerator();
        }
    
        public IFileEnumerator Where(Func predicate)
        {
            return new MemoryEnumerator(items.Where(predicate));
        }
    }
    

提交回复
热议问题