EnumerableTableSource.cs 1.7 KB

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