Wiliam Cardoso
Wiliam Cardoso

Reputation: 444

Add existing object to list

I have an Order class which contains a List<Album> property. In initialization I have a list of Albums:

var albums = new List<Album>
{
    new Album { ArtistId = 2, GenreId = 2, Price = 9.99m, Title = "Mine is Yours" },
    new Album { ArtistId = 2, GenreId = 2, Price = 9.99m, Title = "Robbers & Cowards" },
    new Album { ArtistId = 2, GenreId = 2, Price = 9.99m, Title = "Hold My Home" }
};

Next I have a list of Orders:

var orders = new List<Orders>
{
    new Orders { Albums = //code}
};

What I want to do is be able to add albums from the albums list to the Albums property. Essentially I don't want to be writing Albums = {new Album{//code},{//more code}}. I want to write something like Albums = {{AlbumId = 1}, {AlbumId = 2}}. Etc to add existing albums to the list.

Apologies if badly worded.

Upvotes: 3

Views: 1525

Answers (2)

maccettura
maccettura

Reputation: 10819

You can solve this pretty easily using LINQ:

var orders = new List<Orders>
{
    new Orders { Albums = albums.Where(x => x.AlbumId == 2 || x.AlbumId == 1).ToList() }
};

If you know your ids up front (like in another collection) you could do this:

var albumIds = new [] { 1, 2, 4 };
var orders = new List<Orders>
{
    new Orders { Albums = albums.Where(x => albumIds.Contains(x.AlbumId)).ToList() }
};

Upvotes: 5

Arthur Rizzo
Arthur Rizzo

Reputation: 1357

If you have an Id property in your Album class you can make a dictionary from the initial list you created:

var albumsDict = albums.ToDictionary(a => a.Id);

Then, you can create your orders list like that:

var orders = new List<Orders>
{
    new Orders { Albums = new List<Album>() { albumsDict[1], albumsDict[2], albumsDict[someId] } 
}; 

Upvotes: 1

Related Questions