0

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" }; 
1
  • Did you try anything? What issue you are facing with that ? Commented Sep 17, 2018 at 14:37

4 Answers 4

3

Use SelectMany:

List<string> dtList= dt.AsEnumerable() .SelectMany(r=> new[]{ r.Field<string>("A"), r.Field<string>("B") }) .ToList(); 
Sign up to request clarification or add additional context in comments.

1 Comment

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
2

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();

1 Comment

Creates a List<Object> not List<string>
2

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

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

2 Comments

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.
I'm pretty sure thats the 2nd occurrence of this comment.
2

I know its too late

but you can use this way with help of Newtonsoft Json:

var json = JsonConvert.SerializeObject(dataTable); var YourConvertedDataType = JsonConvert.DeserializeObject<YourDataType>(json); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.