Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable in C# - List type of column and Add method

Tags:

c#

datatable

I created empty DataTable myDT and one of the columns, say Column3 has type List<double>. Now in my code I would like to add sth like this:

myDT.Rows[0]["Column3"].Add(100) 

But I can't use Add method here. What can I do instead? I would like to add elements from different pieces of code to the list in a this specific cell.

like image 748
jujus Avatar asked Oct 20 '25 12:10

jujus


1 Answers

Because of DataTable.Rows[][] might return object type instance instead of List<double> we need to convert the type as your original type List<double> before call Add method.

In your case, I would use as to try to cast the object to your expected type, if that type is List<double> the list will not be null. make sure our code is safer.

var list = dt.Rows[0]["dd"] as List<double>;
if (list != null)
{
    list.Add(100);
}
like image 105
D-Shih Avatar answered Oct 23 '25 01:10

D-Shih



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!