Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set collection inline?

Tags:

c#

.net-4.0

For example:

DataTable table = new DataTable() 
{ 
  Columns = new DataColumnCollection(
     { 
         new DataColumn("col1"), 
         new DataColumn("col2")
     })
});
like image 876
O.O Avatar asked Jan 31 '12 16:01

O.O


2 Answers

You are talking about the Collection Initialiser feature added in C# 3. It is done like this:

DataTable table = new DataTable() 
{ 
    Columns = 
    { 
        new DataColumn("col1"), 
        new DataColumn("col2")
    }
};

This does not call a collection constructor, it uses the collection which already exists in the DataTable.

This is short-hand for Columns.Add(), so it doesn't require Columns to have a setter.

You were so close with the code in your question!

like image 78
Buh Buh Avatar answered Nov 18 '22 14:11

Buh Buh


The Columns property does not have a setter so you can only modify it.

How about this:

DataTable table = new DataTable();
table.Columns.AddRange(new[] { new DataColumn("col1"), new DataColumn("col2") });

If you want to do with one statement in a lambda:

DataTable table = (() => {
    var table = new DataTable();
    table.Columns.AddRange(new[] { new DataColumn("col1"),
                                   new DataColumn("col2") });
    return table;})();
like image 32
Gabe Avatar answered Nov 18 '22 13:11

Gabe