加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用linq将列添加到当前DataTable

发布时间:2020-12-15 17:19:33 所属栏目:百科 来源:网络整理
导读:我们可以添加一个新的Column,它是在现有DataTable中计算的Column dt1.Rows.Add(new string[] { "1","a","a1" });dt1 = (from r in dt1.AsEnumerable()select new {col3 = r.Fieldstring("col1") + r.Fieldstring("col2") }); 结果DataTable应包含新列 解决方
我们可以添加一个新的Column,它是在现有DataTable中计算的Column

dt1.Rows.Add(new string[] { "1","a","a1" });

dt1 = (from r in dt1.AsEnumerable()
select new {
col3 = r.Field<string>("col1") + r.Field<string>("col2") 
});

结果DataTable应包含新列

解决方法

是的,但不是通过LINQ:

DataColumn col3 = new DataColumn();
col3.DataType = typeof(decimal); // or something suitable
col3.ColumnName = "sum";
col3.Expression = "col1 + col2";
dt1.Columns.Add(col3);

您也可以使用LINQ方法创建投影,但这不会更改表(因此分配给dt1是一个错误).从技术上讲,你可以编写一个表达式解析器来为你编写.Expression,但我看不出这是一个很好的时间投入.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读