3

I'm sorry about 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 won't work because I can't type the array. Is there any way to easily fix the code above or, in general, convert System.Collections.Array to System.Collections.Generic.List?

Dervin Thunk
  • 19,515
  • 28
  • 127
  • 217

4 Answers4

6

Make sure you're using System.Linq; and then change your line to:

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

Edit: You could also iterate over the array and add each item individually.

Edit Again: Yet another option to simply cast your array as object[] and either use the ToList() function or pass it into the List<object> constructor:

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

or

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

Joseph Daigle
  • 47,650
  • 10
  • 49
  • 73
2

Can you just change your property declaration to this? :

public object[] Values { get; set; }
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

using System.Linq; ...

    public object[] Values
    {
        get;
        set;
    }

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

        return vals;
    }
Tion
  • 1,470
  • 17
  • 27
0

If you don't want to use linq you can simply cast:

vals.AddRange((IEnumerable<object>) this.Values);
zoidbeck
  • 4,091
  • 1
  • 26
  • 25