ShellColumns.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using InABox.Core;
  6. namespace InABox.Avalonia
  7. {
  8. public class ShellColumn<TEntity>
  9. where TEntity : Entity
  10. {
  11. public int Index { get; }
  12. public Expression<Func<TEntity, object?>> Expression { get; }
  13. public string ColumnName { get; }
  14. public ShellColumn(int index, Expression<Func<TEntity, object?>> expression)
  15. {
  16. Index = index;
  17. Expression = expression;
  18. ColumnName = CoreUtils.GetFullPropertyName(expression, ".");
  19. }
  20. }
  21. public class ShellColumns<TParent,TEntity> : IShellColumns<TEntity> where TEntity : Entity
  22. {
  23. private static Dictionary<string, ShellColumn<TEntity>> _columns = new();
  24. public int IndexOf(string name) => _columns[name].Index;
  25. public string this[string name] => _columns[name].ColumnName;
  26. public ShellColumns<TParent,TEntity> Map(string property, Expression<Func<TEntity, object?>> expression)
  27. {
  28. int iCol = _columns.Keys.Count;
  29. if(_columns.TryGetValue(property, out var column))
  30. {
  31. iCol = column.Index;
  32. }
  33. _columns[property] = new(iCol, expression);
  34. return this;
  35. }
  36. public string? FindShellProperty(string entityProperty)
  37. {
  38. foreach(var (property, column) in _columns)
  39. {
  40. if(column.ColumnName == entityProperty)
  41. {
  42. return property;
  43. }
  44. }
  45. return null;
  46. }
  47. public Columns<TEntity> Columns
  48. {
  49. get
  50. {
  51. var columns = new Columns<TEntity>(ColumnTypeFlags.None).Add(_columns.Values.Select(x => x.ColumnName));
  52. columns.Add(new Columns<TEntity>(ColumnTypeFlags.Required)); // Have to be added after the other columns to preserve column indexing.
  53. return columns;
  54. }
  55. }
  56. public int Count => _columns.Count;
  57. }
  58. }