Question

I have a below method in dataService layer:

public  DataTable retTable ()
    {            
            DataTable dt = new DataTable();
            adap.Fill(dt);
            return dt;                       

    }

because I should add (using Data) name space in business layer. I wanna change it to:

public List<DataTable> retTable()
    {

        DataTable dt = new DataTable();
        adap.Fill(dt);
        List<DataTable> lst = new List<DataTable>();
        lst.AddRange(dt);
        return lst ;

    }

but I have error in

lst.AddRange(dt);

how can i solve it?

Was it helpful?

Solution 3

because table is 2D matrix, so we should return 2D List:

public List<List<string >> retListTable()
    {

        DataTable dt = new DataTable();
        adap.Fill(dt);

        List<List<string>> lstTable = new List<List<string>>();

        foreach (DataRow row in dt.Rows)
        {
            List<string> lstRow = new List<string>();
            foreach (var item in row.ItemArray )
            {
                lstRow.Add(item.ToString().Replace("\r\n", string.Empty));
            }
            lstTable.Add(lstRow );
        }

        return lstTable ;

    }

OTHER TIPS

This would solve the problem

lst.Add(dt);

By AddRange(dt) you can add a collection of DataTables.

However DataSet itself is a collection of DataTables. Then why reinventing the wheel by using List. Simply return DataSet like this

public DataSet retSet()
{
    DataSet ds = new DataSet();
    adap.Fill(ds);
    return ds;
}

Even after you still want to return list you can do

public List<DataTable> retTable()
{
    DataSet dt = new DataSet();
    adap.Fill(ds);
    List<DataTable> lst = new List<DataTable>();
    lst.AddRange(ds.Tables.AsEnumerable());
    return lst;
}

try below

public List<DataRow> retTable()
{
    DataTable dt = new DataTable();
    adap.Fill(dt);
    return dt.AsEnumerable().ToList();
}

but still you need system.Data because of DataRow

you can use custom class in this case like below

List<MyClass> myClass= new List<MyClass>();

myClass = (from DataRow row in dt.Rows

   select new MyClass
   {
       MyProperty1= row["MyColumn1"].ToString(),
       MyProperty2= row["MyColumn12"].ToString()

   }).ToList();

and then return this list from our method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top