c# - 我可以根据字符搜索将数据表中的一列拆分为多列吗

标签 c# datatable

大家好,我想做的是在 C# 上编写代码,将我的数据表中的特定列拆分为 2 列,如下所示

举个例子

Name   Location
-----  --------
ross    a12u20
charle  b12u25

我希望它是这样的

Name   Location   Unit
-----  --------   -----
ross    a12        u20
charle  b12        u25

这可能吗?

最佳答案

缺少一些信息。

假设 Location 属性的长度始终为 6 个字符,或者该单元从索引 4 开始,这可能是一个快速而肮脏的解决方案:

List<person> source = new List<person>();
//I have created a ficitive class person with 2 properties: Name, Location
source.Add(new person { Name ="Ross", Location="a12u15"});
source.Add(new person { Name ="bald", Location="b12u20"});
source.Add(new person { Name ="fat", Location="c12u25"});
source.Add(new person { Name ="man", Location="d12u30"});
source.Add(new person { Name ="heinz", Location="e12u35"});


var result = source.Select(s => new {
    Name = s.Name,
    Location = s.Location.Substring(0,3),
    Unit = s.Location.Substring(3,3)
});

编辑:要从数据表中读取,查询看起来会有所不同。 source 将是您的数据表。

var result = source.Select(s => new {
    Name = s.Field<string>("Name"),
    Location = s.Field<string>("Location").Substring(0,3),
    Unit = s.Field<string>("Location").Substring(3,3)
});

关于c# - 我可以根据字符搜索将数据表中的一列拆分为多列吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19558802/

相关文章:

c# - 不删除现有文件

.net - 左排除加入在 vb.net 中使用 LINQ

html - 测试 HTML 表格是否用于布局与数据?

php - 无法过滤 Laravel 数据表中的关系

c# - 添加(a,b)和 a.add(b)

c# - 将属性名称有空格的json对象从c#发布到第三方api

c# - build DAL。使用 EDM(来自数据库)

c# Panel with auto scroll - 在控件焦点上重置滚动条位置

python-3.x - 如何使用 Dash 在具有大型数据帧的数据表中提供分页

c# - 以编程方式在 Listview 中选择项目,该项目绑定(bind)到数据表并且默认按排序顺序排列?