|
| 1 | +using System.Reflection; |
1 | 2 | using System.Text; |
2 | 3 |
|
3 | 4 | namespace CosmoSQLClient.Core; |
@@ -31,6 +32,60 @@ public static SqlDataTable From(string name, IReadOnlyList<SqlRow> rows) |
31 | 32 | public SqlValue Cell(int row, int col) => Rows[row][col]; |
32 | 33 | public SqlValue Cell(int row, string col) => Rows[row][col]; |
33 | 34 |
|
| 35 | + /// <summary> |
| 36 | + /// Maps each row to an instance of <typeparamref name="T"/> by matching column names |
| 37 | + /// to public settable properties (case-insensitive). Works like Dapper / Swift Codable. |
| 38 | + /// </summary> |
| 39 | + public List<T> ToList<T>() where T : new() |
| 40 | + { |
| 41 | + var props = typeof(T) |
| 42 | + .GetProperties(BindingFlags.Public | BindingFlags.Instance) |
| 43 | + .Where(p => p.CanWrite) |
| 44 | + .ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase); |
| 45 | + |
| 46 | + // Pre-resolve column index → property mapping once |
| 47 | + var map = Columns |
| 48 | + .Select((col, idx) => (idx, prop: props.GetValueOrDefault(col.Name))) |
| 49 | + .Where(x => x.prop is not null) |
| 50 | + .ToList(); |
| 51 | + |
| 52 | + var result = new List<T>(Rows.Count); |
| 53 | + foreach (var row in Rows) |
| 54 | + { |
| 55 | + var obj = new T(); |
| 56 | + foreach (var (idx, prop) in map) |
| 57 | + SetProperty(obj, prop!, row[idx]); |
| 58 | + result.Add(obj); |
| 59 | + } |
| 60 | + return result; |
| 61 | + } |
| 62 | + |
| 63 | + private static void SetProperty(object obj, PropertyInfo prop, SqlValue value) |
| 64 | + { |
| 65 | + if (value.IsNull) return; // leave default for nulls |
| 66 | + |
| 67 | + var t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; |
| 68 | + |
| 69 | + object? v = Type.GetTypeCode(t) switch |
| 70 | + { |
| 71 | + TypeCode.Boolean => value.AsBool(), |
| 72 | + TypeCode.SByte => (sbyte?)value.AsInt(), |
| 73 | + TypeCode.Int16 => (short?)value.AsInt(), |
| 74 | + TypeCode.Int32 => (int?)value.AsInt(), |
| 75 | + TypeCode.Int64 => value.AsInt(), |
| 76 | + TypeCode.Single => (float?)value.AsDouble(), |
| 77 | + TypeCode.Double => value.AsDouble(), |
| 78 | + TypeCode.Decimal => value.AsDecimal(), |
| 79 | + TypeCode.String => value.AsString(), |
| 80 | + TypeCode.DateTime => value.AsDate(), |
| 81 | + _ when t == typeof(Guid) => value.AsGuid(), |
| 82 | + _ when t == typeof(byte[]) => value.AsBytes(), |
| 83 | + _ => value.AsString() |
| 84 | + }; |
| 85 | + |
| 86 | + if (v is not null) prop.SetValue(obj, v); |
| 87 | + } |
| 88 | + |
34 | 89 | /// <summary>Render as a Markdown table string.</summary> |
35 | 90 | public string ToMarkdownTable() |
36 | 91 | { |
|
0 commit comments