我有3列的數據表:拆分一個數據行成多個數據行
Name age profession
John|James|Billy 25|31|28 professor
我想爲了分割該行有3行:
Name age profession
John 25 professor
James 31 professor
Billy 28 professor
我有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);
}
}
謝謝你@TimShmelter !!! – Zack09
假設你想在這裏設置了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)
};
}
}
}
你嘗試過什麼嗎? –
你的下一個問題是什麼?是'我有3條DataRows我需要合併成一條?'。嘗試用代碼發佈你的問題。我們會盡力幫助你 –