Analysis of the method of transforming DataTable into Listless thanTgreater than in C

  • 2021-11-13 02:28:25
  • OfStack

Preface

Usually we need to convert DataTable to List at DAL layer < T > Let the caller use it as well as possible, and try not to care about the fields of the database, so we generally pass List < T > Not DataTable.

Benefits of generics: It adds tremendous effectiveness and flexibility to writing object-oriented programs in the c # language. Boxing and unpacking value types or reference types are not forced. When it comes to the conversion between the two, it is somewhat tedious. The main problem lies in the storage mode of the two. DataTable The storage mode adopts a 2-dimensional table to store data, DataTable 1 table representing data in memory. In List Collection, List The essence is an array, and a linear structure is used to store data.

In the conversion process, the main problem lies in the processing of different types, which are mainly divided into two categories: value type and reference type.

A value type in C # always contains one value corresponding to that type, which means that the type includes: simple type (Simple types), structure type (struct types), enumerated type (Enumeration types).

Simple types include: integer, Boolean, character (a special case of integer), floating-point, decimal. Integers contain: sbyte , byte , short , ushort , int , uint , DataTable0 , ulong And char . Reference types: Reference types do not store the actual data they represent, but they store references to the actual data. Mainly includes: object type, class type, interface, representative element, string type and array.

The conversion code is provided for reference only:

1. Enumeration of types:


 /// <summary>
 ///  Type enumeration 
 /// </summary>
 private enum ModelType
 {
 // Value type 
 Struct,
 Enum,
 // Reference type 
 String,
 Object,
 Else
 }


 private static ModelType GetModelType(Type modelType)
 {
 // Value type 
 if (modelType.IsEnum)
 {
 return ModelType.Enum;
 }
 // Value type 
 if (modelType.IsValueType)
 {
 return ModelType.Struct;
 }
 // Reference type   Special type processing 
 if (modelType == typeof(string))
 {
 return ModelType.String;
 }
 // Reference type   Special type processing 
 return modelType == typeof(object) ? ModelType.Object : ModelType.Else;
 }

2. Specific conversion operation method:


 /// <summary>
 /// datatable Convert to List<T> Set 
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="table"></param>
 /// <returns></returns>
 public static List<T> DataTableToList<T>(DataTable table)
 {
 var list = new List<T>();
 foreach (DataRow item in table.Rows)
 {
 list.Add(DataRowToModel<T>(item));
 }
 return list;
 }

 public static T DataRowToModel<T>(DataRow row)
 {
 T model;
 var type = typeof(T);
 var modelType = GetModelType(type);
 switch (modelType)
 {
 // Value type 
 case ModelType.Struct:
 {
 model = default(T);
 if (row[0] != null)
 model = (T)row[0];
 }
 break;
 // Value type 
 case ModelType.Enum:
 {
 model = default(T);
 if (row[0] != null)
 {
 var fiType = row[0].GetType();
 if (fiType == typeof(int))
 {
 model = (T)row[0];
 }
 else if (fiType == typeof(string))
 {
 model = (T)Enum.Parse(typeof(T), row[0].ToString());
 }
 }
 }
 break;
 // Reference type  c# Right string Also treated as a value type 
 case ModelType.String:
 {
 model = default(T);
 if (row[0] != null)
 model = (T)row[0];
 }
 break;
 // Reference type   Go directly back to the first 1 Line number 1 The value of the column 
 case ModelType.Object:
 {
 model = default(T);
 if (row[0] != null)
 model = (T)row[0];
 }
 break;
 // Reference type 
 case ModelType.Else:
 {
 // Reference type   You must instantiate a generic 
 model = Activator.CreateInstance<T>();
 // Get model Attributes in 
 var modelPropertyInfos = type.GetProperties();
 // Traversal model Every 1 Attributes and assign values DataRow Corresponding column 
 foreach (var pi in modelPropertyInfos)
 {
 // Get the property name 
 var name = pi.Name;
 if (!row.Table.Columns.Contains(name) || row[name] == null) continue;
 var piType = GetModelType(pi.PropertyType);
 switch (piType)
 {
 case ModelType.Struct:
  {
  var value = Convert.ChangeType(row[name], pi.PropertyType);
  pi.SetValue(model, value, null);
  }
  break;
 case ModelType.Enum:
  {
  var fiType = row[0].GetType();
  if (fiType == typeof(int))
  {
  pi.SetValue(model, row[name], null);
  }
  else if (fiType == typeof(string))
  {
  var value = (T)Enum.Parse(typeof(T), row[name].ToString());
  if (value != null)
  pi.SetValue(model, value, null);
  }
  }
  break;
 case ModelType.String:
  {
  var value = Convert.ChangeType(row[name], pi.PropertyType);
  pi.SetValue(model, value, null);
  }
  break;
 case ModelType.Object:
  {
  pi.SetValue(model, row[name], null);
  }
  break;
 case ModelType.Else:
  throw new Exception(" This type conversion is not supported ");
 default:
  throw new Exception(" Unknown type ");
 }
 }
 }
 break;
 default:
 model = default(T);
 break;
 }
 return model;
 }

Summarize

In the above operations, there are corresponding processing methods for different types. Well, the above is the whole content of this article. I hope the content of this article can bring 1 certain help to your study or work. If you have any questions, you can leave a message for communication.


Related articles: