【问题标题】:Optimization of foreach statement, create new mapped Viewmodel list优化foreach语句,新建映射的Viewmodel列表
【发布时间】:2014-07-19 12:14:16
【问题描述】:

有人可以看看我的代码,我认为必须有一种方法来优化 foreach 代码段?

我有一个Artists 的数据库,每个艺术家有多个歌曲标题(称为Titles),每个标题可以有多个Meanings

Artist [1..*] Title [1..*] Meaning [0..*]

我想根据Title 查找ArtistMeanings 计数,并将其作为新的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


    【解决方案1】:

    好的,我读到最好执行 .AddRange 然后每次都使用 .Add 添加项目。 我的代码如下:

     public int CountMeanings(IEnumerable<Meaning> meanings)
        {
            if (meanings != null && meanings.Count() > 0)
                return meanings.Count();
            return 0;
        }
    
        public List<TitleVM> GetTitlesByArtistID(int artistID)
        {
            var titleVMList = new List<TitleVM>();
            var titles = context.Titles.Where(x => x.ArtistID == artistID).AsEnumerable();
            titleVMList.AddRange(titles.Select(item => new TitleVM {
                                   TitleID = item.TitleID,
                                   MeaningCount = CountMeanings(item.Meanings)
                               }));
            return titleVMList;
        }
    

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 2021-08-26
      • 2022-01-01
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多