9

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..

Community
  • 1
  • 1
Rojalin
  • 91
  • 1
  • 1
  • 2

3 Answers3

11
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);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    I like this, but prefer `result.Add( new Foo() { Prop1 = reader.GetInt32(0), Prop2 = reader.GetString(1) } );` – Justin Oct 28 '15 at 17:16
1

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;
        }
Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

Old discussion, but try this on for size.

Strongly type your fields, and cast your rows into a DbDataRecord object. ex:

                    Dim _Query = (From row In _Results.Cast(Of DbDataRecord)().AsParallel()
                            Select New uTyping.Profile() With {
                                .Id = row(0),
                                .Firstname = row(6)
                            }).ToList()
Kevin
  • 2,684
  • 6
  • 35
  • 64