user175084
user175084

Reputation: 4630

Add a List<object> into an object.Array

I have a simple way to put 2 known profiles in my profileArray list as shown below:

Parameters params = new Parameters();
params.plist = new Plist();
params.plist.profileArray = new[]
        {
            new Profile{name = "john", age = 12, country = "USA"},
            new Profile{name = "Brad", age = 20, country = "USA"}
        };

Now i have a

List<Profiles> UserProfiles

which has a bunch of profiles in it.

How do i add this list to params.plist.profileArray?

Any help is appreciated.

Thanks.

This is what is in UserProfile:

List<Profiles> UserProfiles 
foreach(Profiles userProfile in UserProfiles)
{
string name = userProfile.Name;
string age = userProfile.Age;
string country = userProfile.Country;
string sex = userProfile.Sex;
string isMarried = userProfile.IsMarried;
}

Upvotes: 0

Views: 92

Answers (4)

Enigmativity
Enigmativity

Reputation: 117055

Try this:

params.plist.profileArray = UserProfiles.ToArray();

How about this?

params.plist.profileArray =
    UserProfiles
        .Select(up => new
        {
            name = up.Name,
            age = up.Age,
            country = up.Country,
        })
        .ToArray();

Upvotes: 1

Arjan Einbu
Arjan Einbu

Reputation: 13672

Since you're using an array (and arrays in C# are of fixed size), you'l need to create a new array with the combined data.

There are several ways to do this, the simplest would probably be something like this:

var newList = new List<Profile>();
newList.AddRange(params.plist.profileArray);
newList.AddRange(UserProfiles);

params.plist.profileArray = newList.ToArray();

If can you change the implementation of Plist, I would recommend changing the array to a List<Profile>. Then the code would look like this instead:

params.plist.profileArray.AddRange(UserProfiles);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use Enumerable.ToArray:

params.plist.profileArray = UserProfiles.ToArray();

If you want to add the list to the array, an array cannot be modified, you have to create a new one, for example by using Enumerable.Concat:

var newProfile = params.plist.profileArray.Concat(UserProfiles);
params.plist.profileArray = newProfile.ToArray();

Since these are two different classes with similar properties:

var profiles = UserProfiles
   .Select(up => new Profile{name = up.Name, age = up.Age, country = up.Country});
var newProfile = params.plist.profileArray.Concat(profiles);
params.plist.profileArray = newProfile.ToArray();

Upvotes: 3

Nicholas Carey
Nicholas Carey

Reputation: 74257

Try

params.plist.profileArray = params
                            .plist
                            .profileArray
                            .Concat( UserProfiles )
                            .ToArray()
                            ;

Upvotes: 0

Related Questions