将数据行拆分为多个数据行

时间:2013-07-15 13:41:30

标签: c# .net datatable datarow datacolumn

我有一个包含3列的数据表:

Name                     age               profession 

John|James|Billy        25|31|28           professor 

我想分割这一行,以便有3行:

Name                     age               profession 

John                     25                professor
James                    31                professor
Billy                    28                professor

2 个答案:

答案 0 :(得分:2)

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);
    }
}

答案 1 :(得分:1)

假设你想要一个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)
                };
        }
    }
}