C#, DataTable to ArrayList?

前端 未结 5 1745
感情败类
感情败类 2020-12-11 04:19

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

5条回答
  •  遥遥无期
    2020-12-11 04:47

    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 models = new List();
    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 models = dt.Rows
        .Cast()
        .Select(row => new MyModel { 
            Id = (int)row[0],
            Prop1 = (string)row[1],
            Prop2 = (string)row[2]
        })
        .ToList();
    

提交回复
热议问题