Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i convert sqlDatareader to List<> [duplicate]

Tags:

c#

Possible Duplicate:
How can I easily convert DataReader to List<T>?

I want to return list which will store the sqldatareader value. how can i do this..

like image 955
Rojalin Avatar asked Feb 03 '23 03:02

Rojalin


2 Answers

using (var reader = cmd.ExecuteReader())
{
    var result = new List<Foo>();
    while (reader.Read())
    {
        var foo = new Foo 
        {
            Prop1 = reader.GetInt32(0),
            Prop2 = reader.GetString(1),
        }
        result.Add(foo);
    }
}
like image 86
Darin Dimitrov Avatar answered Feb 07 '23 12:02

Darin Dimitrov


Also check this previously asked qestion : How can I easily convert DataReader to List<T>?

Check this for generic type :

public ConvertToList<T>(SqlDataReader sqldr, int index)
        {
            List<T> list = new List<T>();

            while (sqldr.Read())           {
               list.Add((T)sqldr.GetValue(index));               index++;   
            }

            return list;
        }
like image 45
Pranay Rana Avatar answered Feb 07 '23 12:02

Pranay Rana