using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Elwig.Models.Dtos { public class DataTable { public string Name { get; set; } public string FullName { get; set; } public IEnumerable Rows { get; private set; } public int RowNum => Rows.Count(); public IEnumerable ColumnNames => _fieldMap.Select(m => m.Item2); public int ColNum => ColumnNames.Count(); private readonly FieldInfo[] _fields; private readonly (FieldInfo, string)[] _fieldMap; public DataTable(string name, string fullName, IEnumerable rows, IEnumerable<(string, string)>? colNames = null) { _fields = typeof(T).GetFields(); var dict = colNames?.ToDictionary(n => n.Item1, n => n.Item2); _fieldMap = (dict == null ? _fields.Select(f => (f, f.Name)) : _fields.Select(f => (f, dict[f.Name]))).ToArray(); Name = name; FullName = fullName; Rows = rows; } public DataTable(string name, IEnumerable rows, IEnumerable<(string, string)>? colNames = null) : this(name, name, rows, colNames) { } protected IEnumerable<(string, object?)> GetNamedRowData(T row) { return _fieldMap.Select(i => (i.Item2, i.Item1.GetValue(row))); } protected IEnumerable GetRowData(T row) { return GetNamedRowData(row).Select(i => i.Item2); } public IEnumerable> GetData() { return Rows.Select(GetRowData); } public IEnumerable> GetNamedData() { return Rows.Select(GetNamedRowData); } } }