Models: Add Dtos/
This commit is contained in:
45
Elwig/Models/Dtos/DataTable.cs
Normal file
45
Elwig/Models/Dtos/DataTable.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user