8

I have a datatable with few rows each row has few columns.
I want to create an arraylist that countain all row as a string
so each array item look like this {1;qwqww;qweqweqwe;qweqweqw;qwe}
The items in the string will be separated with ; and it is a .NET 2 solution

Thanks

Himanshu Jansari
  • 30,115
  • 28
  • 106
  • 129
Data-Base
  • 8,088
  • 35
  • 72
  • 96

5 Answers5

10

Here is a solution that actually works.

ArrayList rows = new ArrayList();

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

However, I feel I should point out that it is unwise to use the obsolete ArrayList. Use List<string> instead, since the rows are strings:

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

The rest of the code is the same.

Nick Binnet
  • 1,839
  • 7
  • 31
  • 48
Timwi
  • 63,217
  • 30
  • 158
  • 225
  • 1
    Thanks, but dataRow.ItemArray.Select(item => item.ToString) does not work for me! I'm using .NET v2 is there any thing to do with it ? – Data-Base Aug 26 '10 at 10:04
  • @Data-Base: Add `using System.Linq;` at the top of the file. – Timwi Aug 27 '10 at 04:20
1

Instead of using an ArrayList I would recommend you using a strongly typed collection because an ArrayList wouldn't bring much value compared to a non-strongly typed DataTable. So you could 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 over your DataTable and fill 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 could use LINQ if you prefer:

List<MyModel> models = dt.Rows
    .Cast<DataRow>()
    .Select(row => new MyModel { 
        Id = (int)row[0],
        Prop1 = (string)row[1],
        Prop2 = (string)row[2]
    })
    .ToList();
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
1
ArrayList rows = new ArrayList();

foreach (DataRow dataRow in ((DataTable)dataGrid.DataSource).Rows)
{
    rows.Add(String.Join(";", (string[])dataRow.ItemArray));
}
thelost
  • 6,488
  • 3
  • 26
  • 43
0

Here's my theory: This is a code fragment that I use to write a CSV for a datatable:

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...

thelost
  • 6,488
  • 3
  • 26
  • 43
MikeAinOz
  • 104
  • 1
  • 9
  • 23
-2
ArrayList aList = new ArrayList(dt.Rows.Count);
foreach (DataRow row in dt.Rows)
{
    aList.Add(row);
}
Anil Soman
  • 2,397
  • 7
  • 36
  • 63