Best method to use IDataReader as IEnumerable?

后端 未结 6 857
攒了一身酷
攒了一身酷 2021-02-06 13:16

I need to use Linq on any IDataReader implementations like this

var c = sqlDataReader.AsEnumerable().Count();

Example:

<
6条回答
  •  终归单人心
    2021-02-06 13:54

    Try, this:

    public static class DataReaderExtension
    {
        public class EnumeratorWrapper
        {
            private readonly Func moveNext;
            private readonly Func current;
    
            public EnumeratorWrapper(Func moveNext, Func current)
            {
                this.moveNext = moveNext;
                this.current = current;
            }
    
            public EnumeratorWrapper GetEnumerator()
            {
                return this;
            }
    
            public bool MoveNext()
            {
                return moveNext();
            }
    
            public T Current
            {
                get { return current(); }
            }
        }
    
        private static IEnumerable BuildEnumerable(
                Func moveNext, Func current)
        {
            var po = new EnumeratorWrapper(moveNext, current);
            foreach (var s in po)
                yield return s;
        }
    
        public static IEnumerable AsEnumerable(this T source) where T : IDataReader
        {
            return BuildEnumerable(source.Read, () => source);
        }
    }
    

提交回复
热议问题