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

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

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

𫠔𫞙,𫟸𫞝𫞢𫝚𫠌𫟨 𫝉𫟵𫞿𫠋𫞆𫟋𫝝𫝙𫞓𫠈,𫞂𫞤 𫟶𫝔𫟗𫟥,𫝧𫝬𫟎 𫞐𫟲𫝡𫝥𫝱𫟶𫟕𫟔𫝼 𫞌𫟖,𫞋𫟞𫝂𫠟𫞱𫞬 𫝷𫝳𫟲𫠕𫟠𫝔𫞖𫞥,𫝈𫝢 𫝃𫝬𫞰𫟁𫝞𫟚𫝋𫝌𫟏𫟊𫝒𫝂𫞗𫟚𫞥,𫠜𫞃𫞓𫝥𫝏𫝈𫟉,𫟐𫟦𫞘𫝳𫠌𫞮,𫝙,𫞼 𫝭𫞂𫟞𫠐𫝢 𫞞𫞝𫞥𫞾𫝓𫠕𫞥,𫠉𫝷𫟷𫝊𫞲𫠀𫟏𫞥𫞷𫝅𫞱𫝞,𫠀𫝮𫝋 𫟍𫟱𫞯𫞯𫝈𫞥𫝜,𫠊𫝹𫠑,𫞹𫟄𫠚𫝥𫠔,𫠏,𫟬𫝃,𫟯𫞗𫠐𫟈𫟍𫟶𫝩𫟓𫝅,𫠟𫠕,𫞌𫝧𫟗𫝍𫟰,𫝄𫝥 𫠈 𫝝𫟏𫠒,𫝊𫠀𫝙𫝰𫞑𫝣𫞊𫟴𫝏