Array for list - Unable to do work AddRange (IEnumerable)

I apologize for the naive question. I have the following:

public Array Values
{
  get;
  set;
}

public List<object> CategoriesToList()
{
  List<object> vals = new List<object>();
  vals.AddRange(this.Values);

    return vals;
}

But this will not work, because I cannot enter an array. Is there a way to easily fix the code above or, in general, convert System.Collections.Array to System.Collections.Generic.List?

+3
source share
4 answers

Make sure you are using System.Linq;, and then change your line to:

vals.AddRange(this.Values.Cast<object>());

Edit: You can also iterate over the array and add each element individually.

Edit Again: Another option is to simply pass your array like object[]either use the function ToList()or pass it to the constructor List<object>:

((object[])this.Values).ToList();

or

new List<object>((object[])this.Values)

+5

?

public object[] Values { get; set; }
+2

System.Linq; ...

    public object[] Values
    {
        get;
        set;
    }

    public List<object> CategoriesToList()
    {
        List<object> vals = new List<object>();
        vals.AddRange(Values.ToList());

        return vals;
    }
0
source

If you do not want to use linq, you can simply click:

vals.AddRange((IEnumerable<object>) this.Values);
0
source

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


All Articles