将现有对象添加到列表

时间:2017-07-18 17:59:11

标签: c# list

我有一个Order类,其中包含List<Album>属性。在初始化中,我有一个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" }
};

接下来我有一个Orders列表:

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

我想要做的是能够将albums列表中的相册添加到Albums属性。基本上我不想写Albums = {new Album{//code},{//more code}}。我想写一些像Albums = {{AlbumId = 1}, {AlbumId = 2}}这样的东西。等将现有专辑添加到列表中。

如果措辞严厉,请道歉。

2 个答案:

答案 0 :(得分:5)

你可以使用LINQ轻松解决这个问题:

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

如果你事先知道你的ids(就像在另一个收藏中那样),你可以这样做:

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

答案 1 :(得分:1)

如果你的Album类中有Id属性,你可以从你创建的初始列表中创建一个字典:

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

然后,您可以创建您的订单列表:

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