Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

how to map datatable to list in c#

public List<T> ConvertToList<T>(DataTable dt)
{
    var columnNames = dt.Columns.Cast<DataColumn>()
            .Select(c => c.ColumnName)
            .ToList();
    var properties = typeof(T).GetProperties();
    return dt.AsEnumerable().Select(row =>
    {
        var objT = Activator.CreateInstance<T>();
        foreach (var pro in properties)
        {
            if (columnNames.Contains(pro.Name))
            {
                 PropertyInfo pI = objT.GetType().GetProperty(pro.Name);
                 pro.SetValue(objT, row[pro.Name] == DBNull.Value ? null : Convert.ChangeType(row[pro.Name], pI.PropertyType));
            }
        }
        return objT;
   }).ToList();
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: new color unity 
Csharp :: get execution directory c# 
Csharp :: c# loop through files in folder 
Csharp :: generate random name c# 
Csharp :: create char array c# 
Csharp :: how to save a c# dictionary 
Csharp :: jarray to list c# 
Csharp :: how to make a specific scene load only on game start in unity 
Csharp :: dotnet ef database update connection string 
Csharp :: unity hide mesh 
Csharp :: how to chagne rotation in unity 
Csharp :: all month in array 
Csharp :: c# mailmessage set sender name 
Csharp :: c# byte array to bitmap 
Csharp :: .net Core Return File like File Server 
Csharp :: selenium open chrome c# 
Csharp :: mvc 5 dropdownlist 
Csharp :: dotnet new project 
Csharp :: C# get key by value Dict 
Csharp :: int value from enum in C# 
Csharp :: c# get command line arguments 
Csharp :: how to set rigidbody velocity in unity 
Csharp :: c# color hex 
Csharp :: c# console wait for input 
Csharp :: c# onmousedown. unity 
Csharp :: unity how to move an object 
Csharp :: enumerable.range contains 
Csharp :: c# adding to a list 
Csharp :: c# multiline comment 
Csharp :: average c# 
ADD CONTENT
Topic
Content
Source link
Name
5+7 =