Best method to use IDataReader as IEnumerable?

后端 未结 6 845
攒了一身酷
攒了一身酷 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:53

    You could create an extension method to do this (see caveats below):

    public static class DataReaderExtension
    {
        public static IEnumerable AsEnumerable(this System.Data.IDataReader source)
        {
            if (source == null)
                throw new ArgumentNullException("source");
    
            while (source.Read())
            {
                Object[] row = new Object[source.FieldCount];
                source.GetValues(row);
                yield return row;
            }
        }
    }
    

    Found here: http://www.thinqlinq.com/default/Consuming-a-DataReader-with-LINQ.aspx


    As pointed out by @LukeH, note that as IDataReader only supports reading once, forwards, you'll only be able to query the enumerable once. (To get round this you could call ToList/ToArray, then query that).

    Note that SqlDataReader already impliments IEnumerable so you won't need to do this in the example you've given.

    Also, be aware that it's probably better to do any filtering/aggrigating on the server (via LINQ to SQL for example)

提交回复
热议问题