C
C#2y 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;
}
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;
}
4 Replies
Aaron
Aaron2y ago
easiest way is to have some base class for ReportSetup, that doesn't have the generic
Dyad
DyadOP2y ago
@vec![atreit; 1024] That's what I figured. For what I'm trying to do, is this the right approach, or is there another way that would be better suited for the task?
Denis
Denis2y ago
No, it should be the approach to do what you said - a base class/interface that would be used to represent said classes in a collection. The question is whether you want the right thing? Is there a real need to have a collection of these different generic class instances?
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server