C#DataTable与List/Json/Dictionary互相转换

知识库

C#DataTable与List/Json/Dictionary互相转换

2023-09-02 17:29


本文将介绍如何在C#中进行DataTable与List、Json、Dictionary之间的相互转换。

                                            
    
    

在C#开发中,经常会遇到需要将DataTable对象与List、Json、Dictionary等类型相互转换的场景。下面将介绍一些常用的方法:

1. DataTable转换为List

可以使用LINQ查询语句将DataTable转换为List:

        
public static List DataTableToList(DataTable dataTable) where T : new()
{
    List list = new List();
    foreach (DataRow row in dataTable.Rows)
    {
        T item = new T();
        foreach (DataColumn column in dataTable.Columns)
        {
            PropertyInfo property = typeof(T).GetProperty(column.ColumnName);
            if (property != null && row[column] != DBNull.Value)
            {
                property.SetValue(item, row[column], null);
            }
        }
        list.Add(item);
    }
    return list;
}
        
    

2. List转换为DataTable

可以使用反射和泛型将List转换为DataTable:

        
public static DataTable ListToDataTable(List list)
{
    DataTable dataTable = new DataTable();
    Type type = typeof(T);
    PropertyInfo[] properties = type.GetProperties();
    foreach (PropertyInfo property in properties)
    {
        dataTable.Columns.Add(property.Name, property.PropertyType);
    }
    foreach (T item in list)
    {
        DataRow row = dataTable.NewRow();
        foreach (PropertyInfo property in properties)
        {
            row[property.Name] = property.GetValue(item, null);
        }
        dataTable.Rows.Add(row);
    }
    return dataTable;
}
        
    

3. DataTable转换为Json

使用Json.Net库可以方便地将DataTable转换为Json字符串:

        
string dataTableJson = JsonConvert.SerializeObject(dataTable);
        
    

4. Json转换为DataTable

同样使用Json.Net库可以将Json字符串转换为DataTable:

        
DataTable dataTable = JsonConvert.DeserializeObject(jsonString);
        
    

5. DataTable转换为Dictionary

可以使用LINQ查询语句将DataTable转换为Dictionary:

        
public static Dictionary DataTableToDictionary(DataTable dataTable, string keyColumnName, string valueColumnName)
{
    return dataTable.AsEnumerable()
        .ToDictionary(row => row.Field(keyColumnName), row => row.Field(valueColumnName));
}
        
    

6. Dictionary转换为DataTable

可以通过创建一个新的DataTable,并将Dictionary中的键值对逐个添加到DataTable的行中:

        
public static DataTable DictionaryToDataTable(Dictionary dictionary)
{
    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("Key", typeof(TKey));
    dataTable.Columns.Add("Value", typeof(TValue));
    foreach (KeyValuePair pair in dictionary)
    {
        dataTable.Rows.Add(pair.Key, pair.Value);
    }
    return dataTable;
}
        
    

标签:
  • C#
  • DataTable
  • List
  • Json
  • Dictionary
  • 转换