Files
ahtol/daq_testing/DataTableHelper.cs
Wesley Hofman ecb076ce8b First Commit
2025-08-29 18:13:03 +02:00

41 lines
1.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp5
{
public static class DataTableHelper
{
public static DataTable ToDataTable<T>(List<T> items)
{
var dataTable = new DataTable(typeof(T).Name);
// Get all properties of the class
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Create DataTable columns based on properties
foreach (var prop in properties)
{
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
// Add rows to DataTable
foreach (var item in items)
{
var values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
}