将一个数据行拆分为多个数据行
本文关键字:数据 拆分 一个 | 更新日期: 2023-09-27 18:22:36
我有一个包含3列的数据表:
Name age profession
John|James|Billy 25|31|28 professor
我想把这一行分成3行:
Name age profession
John 25 professor
James 31 professor
Billy 28 professor
String.Split
和循环是您的朋友。
var tblFlattenedStudents = tblStudents.Clone();
foreach (DataRow row in tblStudents.Rows)
{
var names = row.Field<string>("Name").Split('|');
var ages = row.Field<string>("age").Split('|');
var profession = row.Field<string>("profession");
for (int i = 0; i < names.Length; i++)
{
var newRow = tblFlattenedStudents.Rows.Add();
newRow.SetField("Name", names[i]);
newRow.SetField("age", ages.ElementAtOrDefault(i));
newRow.SetField("profession", profession);
}
}
假设您想要一个POCO而不是一个数据表/数据集,这里有一些写得不好的代码可以满足您的需求。
public class Teacher
{
public string Name { get; set; }
public string Age { get; set; }
public string Profession { get; set; }
public static IEnumerable<Teacher> YieldFromCSV(string nameData, string ageData, string professionData)
{
// you really want to include error checking here
var names = nameData.Split('|');
var ages = ageData.Split('|');
var professions = professionData.Split('|');
for (var i = 0; i < names.Length; i++)
{
yield return new Teacher
{
Name = names[i],
Age = ages.ElementAtOrDefault(i),
Profession = professions.ElementAtOrDefault(i) ?? professions.ElementAtOrDefault(0)
};
}
}
}