Click here to Skip to main content
15,888,733 members
Articles / Database Development / SQL Server
Tip/Trick

DataReader into IEnumerable with C#

Rate me:
Please Sign up or sign in to vote.
4.87/5 (8 votes)
4 Nov 2013CPOL 88.6K   15   19
How to convert any datareader into generic list.

Introduction

This tip shows how to convert DataReader into IEnumerable using C# through reflection.

Background

Converting DataReader into IEnumerable with C# can be useful in these scenarios:

  • Working with LINQ and therefore with IEnumberable lists. 
  • Working with ORM with Code First and getting data from Store Procedures. 

Using the code 

Step 1. To create Reflection method.

Parameters:

  1. One object to copy value property. Observe it's a reference value.
  2. Property Name/Value to set the object.
C#
public class Reflection
{
    public void FillObjectWithProperty(ref object objectTo, string propertyName, object propertyValue)
    {
        Type tOb2 = objectTo.GetType();
        tOb2.GetProperty(propertyName).SetValue(objectTo, propertyValue);
    }
}

Step 2. To create extension method

It is the most complex, we can find many information on Google about extension methods. The function is very detailed.

C#
public static class IENumerableExtensions
{
    public static IEnumerable<T> FromDataReader<T>(this IEnumerable<T> list, DbDataReader dr)
    {
        //Instance reflec object from Reflection class coded above
        Reflection reflec = new Reflection();
        //Declare one "instance" object of Object type and an object list
        Object instance;
        List<Object> lstObj = new List<Object>();
        
        //dataReader loop
       while (dr.Read()){
           //Create an instance of the object needed.
           //The instance is created by obtaining the object type T of the object
           //list, which is the object that calls the extension method
           //Type T is inferred and is instantiated
           instance= Activator.CreateInstance(list.GetType().GetGenericArguments()[0]);
             
           // Loop all the fields of each row of dataReader, and through the object
           // reflector (first step method) fill the object instance with the datareader values
           foreach (DataRow drow in dr.GetSchemaTable().Rows){
               reflec.FillObjectWithProperty(ref instance, 
                       drow.ItemArray[0].ToString(), dr[drow.ItemArray[0].ToString()]);
           }
             
           //Add object instance to list
           lstObj.Add(instance);
       }

       List<t> lstResult = new List<t>();
       foreach (Object item in lstObj){
           lstResult.Add((T)Convert.ChangeType(item, typeof(T)));
       }

       return lstResult;
   }
}</t></t>

Step 3. Sample of call extension method

T: Any Generics Type.  dr: DataReader

C#
List<T> list = new List<T>().FromDataReader(dr).ToList(); 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseVery appreciate your sharing! Pin
Member 1043832919-Dec-19 11:52
Member 1043832919-Dec-19 11:52 
QuestionI need an example Pin
adeangelis30-Apr-15 11:04
adeangelis30-Apr-15 11:04 
SuggestionHow about this instead? Pin
sobo1231-Mar-14 16:47
sobo1231-Mar-14 16:47 
GeneralRe: How about this instead? Pin
Jaume González2-Mar-14 8:36
Jaume González2-Mar-14 8:36 
GeneralRe: How about this instead? Pin
Koopakiller19-Sep-14 4:54
Koopakiller19-Sep-14 4:54 
GeneralThoughts Pin
PIEBALDconsult31-Oct-13 14:20
mvePIEBALDconsult31-Oct-13 14:20 
QuestionSorry man. You are Monkey Two (like me) :( Pin
hollysong31-Oct-13 10:06
hollysong31-Oct-13 10:06 
AnswerRe: Sorry man. You are Monkey Two (like me) :( Pin
Jaume González31-Oct-13 21:22
Jaume González31-Oct-13 21:22 
GeneralRe: Sorry man. You are Monkey Two (like me) :( Pin
Jörgen Andersson19-Apr-14 9:30
professionalJörgen Andersson19-Apr-14 9:30 
QuestionAll a bit unnecessary Pin
Rob Philpott31-Oct-13 2:33
Rob Philpott31-Oct-13 2:33 
AnswerRe: All a bit unnecessary Pin
Jaume González31-Oct-13 3:23
Jaume González31-Oct-13 3:23 
GeneralRe: All a bit unnecessary Pin
Rob Philpott31-Oct-13 3:41
Rob Philpott31-Oct-13 3:41 
GeneralRe: All a bit unnecessary Pin
Jaume González31-Oct-13 5:52
Jaume González31-Oct-13 5:52 
GeneralRe: All a bit unnecessary Pin
Southmountain22-Jun-19 10:34
Southmountain22-Jun-19 10:34 
QuestionAbout the ref Pin
pstjean31-Oct-13 2:26
pstjean31-Oct-13 2:26 
SuggestionTake a Func as Argument Pin
WJasonM31-Oct-13 2:20
WJasonM31-Oct-13 2:20 
GeneralRe: Take a Func as Argument Pin
Jaume González31-Oct-13 3:24
Jaume González31-Oct-13 3:24 
Questionhmm Pin
johannesnestler31-Oct-13 2:15
johannesnestler31-Oct-13 2:15 
AnswerRe: hmm Pin
Jaume González31-Oct-13 3:26
Jaume González31-Oct-13 3:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.