0

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

Name                     age               profession 

John|James|Billy        25|31|28           professor 

我想拆分这一行以获得 3 行:

Name                     age               profession 

John                     25                professor
James                    31                professor
Billy                    28                professor
4

2 回答 2

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);
    }
}
于 2013-07-15T13:51:35.893 回答
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)
                };
        }
    }
}
于 2013-07-15T13:56:03.107 回答