A
A
Alexey2016-04-09 09:07:06
WPF
Alexey, 2016-04-09 09:07:06

How to convert ObservableCollection to DataTable?

Comrades, tell me how it is possible and, preferably, how to correctly convert ObservableCollection to DataTable.
What is the essence:
There is an ObservableCollection with data that needs to be fed to a stored procedure on a SQL server (MS SQL 2008R2)
What I plan to do: create a table with data in a transaction, transfer it to the server, call the stored procedure. Take the data that she returned.
Are there any ways to convert an ObservableCollection to a DataTable without stupidly looping through the collection?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Iron Bug, 2016-04-09
@k1lex

I'm not sure if it's possible to do without overkill. You still have to bypass the values ​​somehow. In addition, the DataTable does not have the ability to set all rows to a strasse, only add one at a time. I can suggest this:

var persons = new ObservableCollection<Person>();
var table = new DataTable("Persons");
var nameCol = new DataColumn("name") {DataType = typeof (string), AllowDBNull = true};
table.Columns.Add(nameCol);
var ageCol = new DataColumn("age") {DataType = typeof (int), AllowDBNull = false};
table.Columns.Add(ageCol);
persons.ToList().ForEach(p =>
{
    var row = table.NewRow();
    row.SetField(nameCol, p.Name);
    row.SetField(ageCol, p.Age);
    table.Rows.Add(row);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question