C# 如何将值添加到现有行的新数据表列中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17366415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:18:42  来源:igfitidea点击:

how can I add values into a new data table column in the existing rows

c#

提问by Mitch

Here Is my problem. I am trying to take the Full Name field of my data table and split the name into first and last then add those names back into my data table in their correct positions. So far this is what I have.

这是我的问题。我试图获取我的数据表的全名字段并将名称拆分为第一个和最后一个,然后将这些名称添加回我的数据表中的正确位置。到目前为止,这就是我所拥有的。

DataTable DBTable = LoadMailingListContent(Location);

List<string> fullNames = DBTable.Rows.OfType<DataRow>().Select(dr => dr.Field<string>(columnName)).ToList();

DBTable.Columns.Remove(columnName);

DBTable.Columns.Add("First Name");
DBTable.Columns.Add("Last Name");

foreach (string fullname in fullNames)
{
    var names = fullname.Split(' ');
    string firstName = names[0];
    string lastName = names[1];

    //here is where I want to add the new name values into their new fields
}

Could I set a counter inside my foreach loop and add the names back in depending on the index of the row? I need help on how to add the new first and last name values back into my new fields.

我可以在 foreach 循环中设置一个计数器并根据行的索引重新添加名称吗?我需要有关如何将新的名字和姓氏值添加回新字段的帮助。

thanks

谢谢

采纳答案by kostas ch.

Try

尝试

DataTable DBTable = LoadMailingListContent(Location);

DataColumn dc = new DataColumn("FirstName");
DBTable.Columns.Add(dc);
dc = new DataColumn("LastName");
DBTable.Columns.Add(dc);
foreach (DataRow d in DBTable.Rows)
{ 
    var names = d["fullname"].ToString().Split(' ');
    d["FirstName"] = names[0];
    d["LastName"] = names[1];
}

回答by Zdravko Danev

DBTable["First Name"] = firstName;
DBTable["Last Name"] = lastName;

回答by Igor

for (int iter = 0; iter < fullNames.Count; iter++)
{
  var names = fullNames[iter].Split(' ');
  string firstName = names[0];
  string lastName = names[1];
  DBTable.Rows[iter]["First Name"] = firstName;
  DBTable.Rows[iter]["Last Name"] = lastName;
}

回答by Vijay Kumbhoje

Below is simple example to add column and its value to existing datatable.

下面是将列及其值添加到现有数据表的简单示例。

string status = "ABC";
        DataColumn dc = new DataColumn("Status");
        dt.Columns.Add(dc);
        foreach (DataRow dr in dt.Rows)
        {
            dr["status"]= status;
        }
        return dt;

The resulting datatable will look like

结果数据表看起来像

ExistingColumn | Status

现有专栏 | 地位

ExistingValue | ABC

现有价值 | 美国广播公司