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

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)