Method Analysis of Converting DataTable to ListT in C#

In C#, the operation of data is a crucial aspect, and it is often necessary to convert data from one form to another to meet our needs. Among them, DataTable and List are two common data forms. DataTable is a tabular data type that stores data in rows and columns. List is a collection type that can store objects of any type, and elements can be added or deleted dynamically. In many cases, we need to convert DataTable into List for subsequent operation and use. This article will introduce how to convert DataTable into ListT in C#, where T represents any required type.

  1. use reflection

Using reflection is a common way to convert DataTable to ListT. Reflection is a type-related programming model that allows programmers to traverse and manipulate metadata within an assembly.

1.1 Create a generic method

First, we need to create a generic method in C# that converts the DataTable into a List. A generic method is a method that can handle any type of parameter.

public static List<T> ConvertDataTableToList<T>(DataTable table) where T : class, new()
{
    List<T> list = new List<T>();

    foreach (DataRow row in table.Rows)
    {
        T obj = new T();
        foreach (PropertyInfo info in obj.GetType().GetProperties())
        {
            if (table.Columns.Contains(info.Name))
            {
                if (row[info.Name] != DBNull.Value)
                {
                    info.SetValue(obj, row[info.Name], null);
                }
            }
        }
        list.Add(obj);
    }
    return list;
}

1.2 Convert DataTable to ListT

Then, we can call the method created above to convert the DataTable into a ListT.

DataTable table = new DataTable();
//添加列,省略

List<MyClass> list = ConvertDataTableToList<MyClass>(table);
  1. Query using LINQ

Instead of using reflection, we can also use LINQ query to convert DataTable to ListT. LINQ query is a powerful query tool that can convert various data into query results within C#. Here we are going to use DataTable's AsEnumerable method and LINQ Select method.

List<MyClass> list = table.AsEnumerable().Select(row =>
        {
            MyClass obj = new MyClass();
            obj.Field1 = row.Field<type>("ColumnName1");
            obj.Field2 = row.Field<type>("ColumnName2");
            obj.Field3 = row.Field<type>("ColumnName3");
            return obj;
        }).ToList();

Among them, type is your field type, and MyClass is the target type you set. In the Select method of Linq, we set the assignment to each field in MyClass when traversing each row. Finally convert the result to a List type.

Summarize:

The above are two methods of converting DataTable to ListT, each has its own advantages and disadvantages, and you can choose the appropriate method according to your needs. Using reflection can handle any type parameter and is very efficient in case of type indetermination, but performance is slightly lower than using LINQ. Using LINQ, you can easily process a large amount of data through statement chains, and the code is more readable.

Whichever approach you choose, it will require careful selection and consideration, with trade-offs in type and performance.

Guess you like

Origin blog.csdn.net/naer_chongya/article/details/130422703