【发布时间】:2014-07-19 12:14:16
【问题描述】:
有人可以看看我的代码,我认为必须有一种方法来优化 foreach 代码段?
我有一个Artists 的数据库,每个艺术家有多个歌曲标题(称为Titles),每个标题可以有多个Meanings。
Artist [1..*] Title [1..*] Meaning [0..*]
我想根据Title 查找Artist 的Meanings 计数,并将其作为新的ViewModel 列表返回。
public class TitleVM
{
public int TitleID { get; set; }
public int MeaningCount { get; set; }
}
public List<TitleVM> GetTitlesByArtistID(int artistID)
{
//find the artist by ID
var titles = context.Titles.Where(x => x.ArtistID == artistID);
//create new VMList to be returned
var titleVMList = new List<TitleVM>();
//loop through each title,
foreach (var item in titles)
{
//find the number of meanings,
var count = 0;
if (item.Meanings != null && item.Meanings.Count > 0)
{
count = item.Meanings.Count();
}
// and map it to VM, add to list
titleVMList.Add(new TitleVM
{
TitleID = TitleID,
MeaningCount = count
});
}
return titleVMList;
}
我认为映射它会最简单,但不知道如何以这种方式将视图模型与列表映射。 在我的项目中,我使用 Omu.ValueInjecter 来映射基本模型,因为 Automapper 需要完全信任才能运行,而我的主机不允许。
如果需要更多信息,请告诉我。
【问题讨论】:
标签: optimization foreach lambda viewmodel