C #, DataTable in ArrayList?

I have a datatable with multiple rows, each row has multiple columns.
I want to create an arraylist that considers the entire string as a string so each element of the array looks like this: {1;qwqww;qweqweqwe;qweqweqw;qwe}
Elements in the string will be separated by a character ; and this is .NET 2 solution

thanks

+7
arraylist c # datatable
source share
5 answers

Here is a solution that really works.

 ArrayList rows = new ArrayList(); foreach (DataRow dataRow in myDataTable.Rows) rows.Add(string.Join(";", dataRow.ItemArray.Select(item => item.ToString()))); 

However, I believe that I should indicate that using an obsolete ArrayList not practical. Use List<string> instead, since strings are strings:

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

The rest of the code is the same.

+10
source share

Instead of using an ArrayList I would recommend that you use a strongly typed collection, because an ArrayList will not bring much value compared to a non-strongly typed DataTable . Therefore, you can start by defining a model that will represent each row:

 public class MyModel { public int Id { get; set; } public string Prop1 { get; set; } public string Prop2 { get; set; } } 

then loop around on the DataTable and populate the collection:

 List<MyModel> models = new List<MyModel>(); foreach (DataRow row in dt.Rows) { MyModel model = new MyModel { Id = (int)row[0], Prop1 = (string)row[1], Prop2 = (string)row[2] }; models.Add(model); } 

Or you can use LINQ if you want:

 List<MyModel> models = dt.Rows .Cast<DataRow>() .Select(row => new MyModel { Id = (int)row[0], Prop1 = (string)row[1], Prop2 = (string)row[2] }) .ToList(); 
+1
source share
 ArrayList rows = new ArrayList(); foreach (DataRow dataRow in ((DataTable)dataGrid.DataSource).Rows) { rows.Add(String.Join(";", (string[])dataRow.ItemArray)); } 
+1
source share

Here is my theory: This is a piece of code that I use to write CSV for data:

 foreach (DataRow row in table.Rows) { for (int i = 0; i < table.Columns.Count; i++) { WriteItem(stream, row[i], quoteall); if (i < table.Columns.Count - 1) stream.Write(','); else stream.Write('\n'); } } 

Use StringBuffer instead of WriteItem ... stream, etc.

0
source share
 ArrayList aList = new ArrayList(dt.Rows.Count); foreach (DataRow row in dt.Rows) { aList.Add(row); } 
-2
source share

All Articles