EnumerableTableSource.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. namespace Terminal.Gui;
  2. /// <summary><see cref="ITableSource"/> implementation that wraps arbitrary data.</summary>
  3. /// <typeparam name="T"></typeparam>
  4. public class EnumerableTableSource<T> : IEnumerableTableSource<T>
  5. {
  6. private readonly T [] data;
  7. private readonly Dictionary<string, Func<T, object>> lambdas;
  8. /// <summary>Creates a new instance of the class that presents <paramref name="data"/> collection as a table.</summary>
  9. /// <remarks>
  10. /// The elements of the <paramref name="data"/> collection are recorded during construction (immutable) but the
  11. /// properties of those objects are permitted to change.
  12. /// </remarks>
  13. /// <param name="data">
  14. /// The data that you want to present. The members of this collection will be frozen after
  15. /// construction.
  16. /// </param>
  17. /// <param name="columnDefinitions">
  18. /// Getter methods for each property you want to present in the table. For example:
  19. /// <code>
  20. /// new () {
  21. /// { "Colname1", (t)=>t.SomeField},
  22. /// { "Colname2", (t)=>t.SomeOtherField}
  23. /// }
  24. /// </code>
  25. /// </param>
  26. public EnumerableTableSource (IEnumerable<T> data, Dictionary<string, Func<T, object>> columnDefinitions)
  27. {
  28. this.data = data.ToArray ();
  29. ColumnNames = columnDefinitions.Keys.ToArray ();
  30. lambdas = columnDefinitions;
  31. }
  32. /// <summary>Gets the object collection hosted by this wrapper.</summary>
  33. public IReadOnlyCollection<T> Data => data.AsReadOnly ();
  34. /// <inheritdoc/>
  35. public object this [int row, int col] => lambdas [ColumnNames [col]] (data [row]);
  36. /// <inheritdoc/>
  37. public int Rows => data.Length;
  38. /// <inheritdoc/>
  39. public int Columns => ColumnNames.Length;
  40. /// <inheritdoc/>
  41. public string [] ColumnNames { get; }
  42. /// <inheritdoc/>
  43. public IEnumerable<T> GetAllObjects () { return Data; }
  44. /// <inheritdoc/>
  45. public T GetObjectOnRow (int row) { return Data.ElementAt (row); }
  46. }