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

Time:05-09

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.

CodePudding user response:

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

CodePudding user response:

If You are using C# 8.0 version, then you can use is operator with Pattern matching, like

if (dt.Rows[0]["Column3"] is List<double> Column3)
{
    Column3.Add(100);
}

CodePudding user response:

You can use .Field instead.

myDT.Rows[0].Field<List<double>>("Column3").Add(100)
  •  Tags:  
  • c#
  • Related