C # - Cannot convert from <DateTime?> To <dynamic>

I am trying to create an attribute in a list that accepts 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 code, I use a list datato store data DateTime?, float?or int?. What can I do to store these different types in the same class attribute?

I get an error message:

Argument 2: cannot convert from 'System.Collections.Generic.List<System.DateTime?>' to 'System.Collections.Generic.List<dynamic>'
+4
source share
4 answers

I would recommend using Generics if you know the type before 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;
    }
}

Using:

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
};
+8
source

I think the change below should work: C

 public List<dynamic> data { get; set; }

WITH

 public dynamic data { get; set; }
+2
source

LINQ :

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

: , ChartData (, , .)

0

If this suits your case, you can use covariant , for example:

IReadOnlyList<dynamic> data;
data = new List<string>();

But it only works with reference types.

If you don't care what type, you can use List for your data.

For easier access, you can use something like this:

private IList data;
public IEnumerable<dynamic> Data { get { return data.OfType<dynamic>(); } }

Hope this helps.

0
source

Source: https://habr.com/ru/post/1676334/


All Articles