EnumerableTableSource.cs 2.0 KB

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