paxcow
paxcow

Reputation: 1941

Store Columns in List sql c#

while (Running)
{
    while (rdr.Read())
    {
        List<PackageDetailFile> pkgFiles = rdr.Read().ToString().ToList();
    }
}

Hello, the read() returns an inner joined table which has 7 8 columns, is it possible to store them inside List ? if we can hows the correct casting of rdr.read(), ( to string to list ... ? )

Upvotes: 1

Views: 534

Answers (2)

Riccardo
Riccardo

Reputation: 1520

try use GetValues method of rdr object. I suppose rdr is a SqlDataReader or another DataReader.

This method return an object array with all columns of the current row. After it you can store the object array in a list of objects. If you want to store in another type of list you must cast every element to the correct type before storing it.

Upvotes: 0

Kane
Kane

Reputation: 16812

Depending on the structure of your PackageDetailFile class and the underlying data you could do something like this

var packageDetailFiles = new List<PackageDetailFile>();

while (Running)
{
    while (rdr.Read())
    {
        var detailFile = new PackageDetailFile();

        // the following will depend on your data structure and class properties
        detailFile.Property1 = rdr.GetString(0);
        detailFile.Property2 = rdr.GetString(1);
        detailFile.Property3 = rdr.GetString(2);

        packageDetailFiles.Add(detailFile);
    }
}

Note: You can use assemblies like AutoMapper to map from a data reader to a POCO reducing the need for the tedious MyObject.MyProperty = dataReader[collectionIndex] making your code far more readable and test friendly.

Upvotes: 1

Related Questions