Models: Add Dtos/

This commit is contained in:
2023-11-12 19:38:36 +01:00
parent 32f229b0a5
commit 2cdde60644
5 changed files with 164 additions and 43 deletions

View File

@ -0,0 +1,45 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Elwig.Models.Dtos {
public class DataTable<T> {
public string Name { get; set; }
public string FullName { get; set; }
public IEnumerable<T> Rows { get; private set; }
public int RowNum => Rows.Count();
public IEnumerable<string> 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<T> 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<T> 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<object?> GetRowData(T row) {
return GetNamedRowData(row).Select(i => i.Item2);
}
public IEnumerable<IEnumerable<object?>> GetData() {
return Rows.Select(GetRowData);
}
public IEnumerable<IEnumerable<(string, object?)>> GetNamedData() {
return Rows.Select(GetNamedRowData);
}
}
}