¿Cómo configurar la colección en línea?

Por ejemplo:

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

preguntado el 31 de enero de 12 a las 16:01

This very much depends on the version of VS/.Net that you're using. -

6 Respuestas

Estás hablando de la Inicializador de colección 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!

Respondido el 31 de enero de 12 a las 21:01

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

Qué tal esto:

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;})();

Respondido el 31 de enero de 12 a las 21:01

I want to do it all inline. I thought it was possible using () => or something. - Oo

You can't do it inline for the reasons I gave in my answer. If you want to keep the code clean you could create an extension method to create a table and add the columns in one step, but at some point it will be at least two lines of code. - D Stanley

If it had a setter, how would it be done? Can you provide a working example please? - Oo

Incluso si Columns had a setter you couldn't do it because there's no constructor for DataColumnCollection that accepts an array of columns. - D Stanley

@DStanley - alright. I guess I probably won't run into those objects very often. I was hoping to see an example (not of datatables) that had a public constructor and public setter. Oh well. - Oo

You probably need to remove the paretheses around that collection initializer for DataColumnCollection, and remove the unmatched, final )

Those are syntactical issues, though. The underlying problems are that the Columns property has no setter, and the DataColumnCollection has no public constructor.

Basically, you have to instantiate and then call .Columns.Add().

If this is something you have to do a lot in your code, you could create helper classes that would give you friendlier syntax:

DataTable table = DataTableFactory.CreateTableWithColumns("col1", "col2");

Respondido el 31 de enero de 12 a las 21:01

I attempted to do this. Even if he correct the syntax error he is going to get an error saying that columnas is a read only property. - Sabueso de seguridad

There are 2 reasons why this won't work:

1) el Columns property is read-only 2) the DataColumnCollection class does not have a constructor that accepts a collection of columns to initialize it.
Best you can do is create the table in one line and add the columns in another:

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

Para responder a su otra pregunta, IF Columns had a setter and IF DataColumnCollection accepted columns in its constructor the syntax would be:

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

Respondido el 31 de enero de 12 a las 21:01

La clase DataColumnCollection has no constructor so you can't manually create an instance. The compiler's error message should be pretty self-explanatory, saying something along the lines of:

The type 'System.Data.DataColumnCollection' has no constructors defined

You can add columns to the DataTable.Columns collection by using the Add() método:

DataTable table = new DataTable();
table.Columns.Add(new DataColumn("col1"));
table.Columns.Add(new DataColumn("col2"));

Respondido el 31 de enero de 12 a las 21:01

You can't use that syntax as the Columns property is readonly. I'd use the technique suggested by Gabe.

Respondido el 31 de enero de 12 a las 21:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.