views:

715

answers:

4

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?

+5  A: 

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
I didn't really want to use Linq for this, but thank you. This is pretty. You deserve acceptance :)
Dervin Thunk
+2  A: 

Can you just change your property declaration to this? :

public object[] Values { get; set; }
Joel Coehoorn
Hi. No, I can't. I'm getting the array from the old Word 2003 API. Unless I'm missing another obvious thing... :(
Dervin Thunk
No - problem. I took another look at it.
Joel Coehoorn
A: 

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
You can actually just pass in `Values` as is since `object[]` is an IEnumerable.
Joseph Daigle
A: 

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

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