Alex
Alex

Reputation: 5724

Create Columns in a datatable with a single expression

I want to define a datatable with columns, where the column definition is part of the datatable definition statement.

Eg

//valid syntax
DataTable dt = new DataTable();
dt.Columns.add("num",typeof(int));
dt.Columns.add("num2",typeof(int));

But I would rather want to do something along the lines of

//invalid syntax
DataTable dt = new DataTable(Data.Columns[] {
    {"num",typeof(int)},
    {"num2",typeof(int)}
};

Is this possible? If it is, what is the correct syntax.

Upvotes: 2

Views: 882

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

You can't initialize DataTable with collection initializer. All you can use is AddRange method of DataColumnCollection, but I don't think its much better than your original approach

DataTable dt = new DataTable();
dt.Columns.AddRange(new[] {
    new DataColumn("num", typeof(int)),
    new DataColumn("num2", typeof(int))
});

You can create extension method which will add columns in fluent way:

public static DataTable AddColumn<T>(this DataTable dt, string name)
{
     dt.Columns.Add(name, typeof(T));
     return dt;
}

Usage:

var dt = new DataTable()
          .AddColumn<int>("num")
          .AddColumn<int>("num2");

Upvotes: 3

Related Questions