EnumerableTableSource.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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> : IEnumerableTableSource<T> {
  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. /// <summary>
  47. /// Gets the object collection hosted by this wrapper.
  48. /// </summary>
  49. public IReadOnlyCollection<T> Data => this.data.AsReadOnly();
  50. /// <inheritdoc/>
  51. public IEnumerable<T> GetAllObjects ()
  52. {
  53. return Data;
  54. }
  55. /// <inheritdoc/>
  56. public T GetObjectOnRow (int row)
  57. {
  58. return Data.ElementAt(row);
  59. }
  60. }
  61. }