C#C
C#3y ago
Dyad

❔ How to create a list of generic objects?

public class Item 
{
  DateTime Date;
  string Name;
  int Age;
}

public class ReportSetup<T>
{
  string Title;
  Func<Item, T> GroupBy;

  public ReportSetup(title, groupBy)
  {
    Title = title;
    GroupBy = groupBy;
  }

  static ReportSetup ByDate = new ReportSetup<DateTime>("By Date", x => x.Date);
  static ReportSetup ByName = new ReportSetup<string>("By Name", x => x.Name);
  static ReportSetup ByAge = new ReportSetup<int>("By Age", x => x.Age);

  //In the UI, I want to be able to display a dropdown with the available report types
  //How do I have a List of generic objects
  static AllReports = new List<ReportSetup<object>>{ ByDate, ByName, ByAge };
}

public class Report<T>
{
  string Title;
  List<ReportRow<T>> Rows;
}

public class ReportRow<T>
{
  T Key;
  List<Item> Items;
}
Was this page helpful?