Пример #1
0
    public static PropertiedObjectList ToListPropertiedObject(this DataTable dataTable)
    {
      List<object> listObject = new List<object>();

      var tableName = dataTable.TableName;
      if (tableName.IsNullOrEmpty() == true)
        tableName = "PropertiedTable";
      var className = tableName;
      var qualClassName = className + "." + className;

      // create an assembly, a module and then a type with the name of the table.
      AssemblyBuilder ab = null;
      ModuleBuilder mb = null;
      {
        var rv = StartAssembly(tableName);
        ab = rv.Item1;
        mb = rv.Item2;
      }

      // namespace Foo { public class Bar { ... } }
      TypeBuilder tb = mb.DefineType(qualClassName,
        TypeAttributes.Public | TypeAttributes.Class);

      // add each of the table columns as a property of the listObject.
      foreach( DataColumn col in dataTable.Columns)
      {
        var pb = tb.AddStringProperty(col.ColumnName);
      }

      // Seal the lid on this type
      Type t = tb.CreateType();

      // loop for each row of the table.
      foreach( DataRow row in dataTable.Rows)
      {
        var classObject = ab.CreateInstance(qualClassName);
        var itemType = classObject.GetType();

        foreach(DataColumn col in dataTable.Columns)
        {
          var s1 = row[col];
          var propName = col.ColumnName;
          itemType.InvokeMember(propName, BindingFlags.SetProperty, null, classObject,
             new Object[] { s1 });
        }

        // add to list of propertied objects.
        listObject.Add(classObject);
      }

      return new PropertiedObjectList(listObject);
    }