Convert DataTable to list

Convert DataTable to list



I have this DataTAble


DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Rows.Add("1", "5");
dt.Rows.Add("6", "10");
dt.Rows.Add("11", "15");



How can I convert this DataTable to get a list like this


List<string> dtList= new List<string> "1", "5", "6", "10", "11", "15" ;






Did you try anything? What issue you are facing with that ?

– Chetan Ranpariya
Sep 17 '18 at 14:37




3 Answers
3



Use SelectMany:


SelectMany


List<string> dtList= dt.AsEnumerable()
.SelectMany(r=> new r.Field<string>("A"), r.Field<string>("B") )
.ToList();






that's perfect, thank you :) also the @Thierry V works perfectly, but I am accepting this answer for data type specification, thank you both of you

– Adnand
Sep 17 '18 at 14:44



Try this:


DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Rows.Add("1", "5");
dt.Rows.Add("6", "10");
dt.Rows.Add("11", "15");
var output = dt.Rows.Cast<DataRow>().SelectMany(x => new x[0], x[1] ).ToList();



Edit: added .ToList();






Creates a List<Object> not List<string>

– Rango
Sep 17 '18 at 14:48


List<Object>


List<string>



Convert to DataRow first by Select, then SelectMany to flatten to an array of object. Finally, convert each value object to string


DataRow


Select


SelectMany


object


string


var list = dt.Select().SelectMany(row => row.ItemArray).Select(x=> (string)x).ToList()






dt.Select() creates a new DataRow(not a list), but i'd use AsEnumerable which doesn't create a new collection, hence saves memory and CPU.

– Rango
Sep 17 '18 at 14:44



dt.Select()


DataRow


AsEnumerable






@TimSchmelter thanks Tim for util information

– Antoine V
Sep 17 '18 at 14:46






I'm pretty sure thats the 2nd occurrence of this comment.

– Drag and Drop
Sep 17 '18 at 14:58



Thanks for contributing an answer to Stack Overflow!



But avoid …



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

Malaysia to Papua New Guinea by motorcycle?

List of Bhojpuri films

.name