Prova questo:
// Create your datatable.
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Street", typeof(double));
// get a list of object arrays corresponding
// to the objects listed in the columns
// in the datatable above.
var result = from item in in this.GetData().Cast<IContent>()
select dt.LoadDataRow(
new object[] { Title = item.GetMetaData("Title"),
Street = item.GetMetaData("Street"),
},
false);
// the end result will be a set of DataRow objects that have been
// loaded into the DataTable.
Articolo originale di codice di esempio: Converting Anonymous type generated by LINQ to a DataTable type
EDIT: Pseudocodice Generico:
void LinqToDatatable(string[] columns, Type[] datatypes, linqSource)
{
for loop
{
dt.columns.add(columns[i], datatypes[i]);
}
//Still thinking how to make this generic..
var result = from item in in this.GetData().Cast<IContent>()
select dt.LoadDataRow(
new object[] { string[0] = item.GetMetaData[string[0]],
string[1] = item.GetMetaData[srring[1]
},
false);
}
fonte
2012-03-30 05:52:05
Cosa stai facendo che hai bisogno di un DataTable come risultato? – dwerner
Sto tentando di esportare in CSV e ho già metodi che possono esportare DataTable/Set in CSV. – TruMan1
Penso che tu stia cercando un linguaggio di programmazione dinamico in uno (principalmente) tipizzato staticamente. Se sei molto legato a questi DataTable alle routine di esportazione csv, allora temo che il tuo percorso possa essere un passo solo per te. Gli oggetti anonimi sono una funzionalità linguistica abbastanza nuova e DataRow/DataTable/DataSet non sono stati progettati per loro. – dwerner