Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - Cannot convert from List<DateTime?> to List<dynamic>

Tags:

c#

list

datetime

I am trying to create an attribute in a list that takes different types. This is my class:

public class ChartData
{
    public string id { get; set; }
    public List<dynamic> data { get; set; }

    public ChartData()
    {
    }

    public ChartData(string id, List<DateTime?> data)
    {
        this.id = id;
        this.data = data;
    }
}

    public ChartData(string id, List<float?> data)
    {
        this.id = id;
        this.data = data;
    }

    public ChartData(string id, List<int?> data)
    {
        this.id = id;
        this.data = data;
    }

In the code I use the data list to store DateTime?, float? or int? data. What do I do to be able to store these different types in one class attribute?

I am getting the error:

Argument 2: cannot convert from 'System.Collections.Generic.List<System.DateTime?>' to 'System.Collections.Generic.List<dynamic>'
like image 786
A. Savva Avatar asked Dec 10 '22 11:12

A. Savva


1 Answers

I would recommend using Generics if you know the type prior to instantiation

public class ChartData
{
   public string id { get; set; }
}

public class ChartData<T> : ChartData
{
    public List<T> data { get; set; }

    public ChartData()
    {
    }

    public ChartData(string id, List<T> data)
    {
        this.id = id;
        this.data = data;
    }
}

Usage:

ChartData<int> intData = new ChartData<int>("ID1", new List<int>());
ChartData<DateTime> dateData = new ChartData<DateTime>("ID1", new List<DateTime>());
ChartData<float> floatData = new ChartData<float>("ID1", new List<float>());



List<ChartData> list = new List<ChartData>() {
    intData,
    dateData,
    floatData
};
like image 109
Oday Fraiwan Avatar answered Dec 30 '22 11:12

Oday Fraiwan