C#DataTable字段值构造

时间:2017-04-28 12:37:18

标签: c# .net c#-4.0

我在C#中有一个带有2个字段的数据表,第一个字段具有Label,它的值也在下一行中。第二个字段只有值。

Field1  Field2
10th    Nick
Nick    John
11th    Marry
John    Andy
Marry   Sandy
12th    null
Andy    null
Sandy   null

我是否有任何方法或逻辑可以应用于构建我的数据以在SQL表中上传,格式如下所示。

Class   Name
10th    Nick
11th    John
11th    Marry
12th    Andy
12th    Sandy

这个数据只是一个例子,但是我需要在大约数百万行中使用数千个类标签来应用逻辑,并寻找可以逐个选择field1值然后在{中搜索该值}的内容。 {1}}

如果找到 - 在field2字段中添加 如果找不到 - 请在Name字段

中添加
class

更好的方法还是代码?正如我所尝试的那样,不幸的是。

1 个答案:

答案 0 :(得分:1)

使用下面的伪代码,您将拥有一个包含类&的自定义对象列表。名字匹配。然后,您可以循环插入数据库。

List<string> classes = new List();
classes.add("10th");
class.add("11th"); //and so on
string currentClass = new String();

SomeObjectWithClassAndName obj = new SomeObjectWithClassAndName();
List<SomeObjectWithClassAndName> myList = new List();

foreach(DataRow row in yourDataTable)
{
   if(classes.Contains(row.Field<string>[1])
   {
      currentClass = row.Field<string>[1];
   }
   else{
      obj = new SomeObject..;
      obj.Class = currentClass;
      obj.Name = row.Field<string>[1];
      MyList.Add(obj);
   }
}