重构重复的Lambda表达式

时间:2013-02-07 13:33:08

标签: c# asp.net-mvc lambda

所以我们有两种方法如下所示:

方法1

private IEnumerable<object> CreateCentreViewModelForExport(IQueryable<CentreTranslation> centreTranslation)
{
    return centreTranslation.Select(s => new
    {
        id = s.Centre.id,
        centreTranslationId = s.id,
        name = s.Centre.name,
        number = s.Centre.number,
        date_opened = s.Centre.date_opened,
        address_line_1 = s.address_line_1,
        address_line_2 = s.address_line_2,
        address_line_3 = s.address_line_3,
        city = s.city,
        county = s.county,
        country = s.Centre.Country.name,
        //country_id = s.Centre.country_id,
        translatedCountry = s.country,
        postcode = s.postcode,
        hidden = !(s.Centre.CentreStatus.Where(w => w.environment_id == 4).FirstOrDefault().active),
        about = s.about,
        virtualTour = s.Centre.virtual_tour,
        directions = s.directions,
        phone = s.Centre.phone,
        fax = s.Centre.fax,
        email = s.Centre.email,
        lat = s.Centre.position.Latitude,
        lng = s.Centre.position.Longitude,
        imageCount = s.Centre.image_count,
        translatedCentreName = s.name,
        amenities = s.amenities ,
        features = s.FeatureTranslations.Select(s2 => new FeatureViewModel()
        {
            id = s2.id,
            name = s2.Feature.name,
            selected = s2.selected
        }),
        businessCentreAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessCentre).FirstOrDefault().about,
        officeSpaceAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.OfficeSpace).FirstOrDefault().about,
        virtualOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.VirtualOffice).FirstOrDefault().about,
        meetingRoomsAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.MeetingRooms).FirstOrDefault().about,
        businessLoungeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessLounge).FirstOrDefault().about,
        dayOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.DayOffice).FirstOrDefault().about,
        language_group = s.Language.language_group,
        culture = s.Language.cuture
    });
}

方法2

private IQueryable<CentreViewModel> CreateCentreViewModel(IQueryable<CentreTranslation> centreTranslation)
{
    return centreTranslation.Select(s => new CentreViewModel()
    {
        id = s.Centre.id,
        centreTranslationId = s.id,
        name = s.Centre.name,
        number = s.Centre.number,
        date_opened = s.Centre.date_opened,
        address_line_1 = s.address_line_1,
        address_line_2 = s.address_line_2,
        address_line_3 = s.address_line_3,
        city = s.city,
        county = s.county,
        //country = s.Centre.Country.name,
        country_id = s.Centre.country_id,
        translatedCountry = s.country,
        postcode = s.postcode,
        hidden = !(s.Centre.CentreStatus.Where(w => w.environment_id == 4).FirstOrDefault().active),
        about = s.about,
        virtualTour = s.Centre.virtual_tour,
        directions = s.directions,
        phone = s.Centre.phone,
        fax = s.Centre.fax,
        email = s.Centre.email,
        lat = s.Centre.position.Latitude,
        lng = s.Centre.position.Longitude,
        imageCount = s.Centre.image_count,
        translatedCentreName = s.name,
        amenities = s.amenities,
        features = s.FeatureTranslations.Select(s2 => new FeatureViewModel()
        {
            id = s2.id,
            name = s2.Feature.name,
            selected = s2.selected
        }),
        businessCentreAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessCentre).FirstOrDefault().about,
        officeSpaceAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.OfficeSpace).FirstOrDefault().about,
        virtualOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.VirtualOffice).FirstOrDefault().about,
        meetingRoomsAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.MeetingRooms).FirstOrDefault().about,
        businessLoungeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessLounge).FirstOrDefault().about,
        dayOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.DayOffice).FirstOrDefault().about
    });
}

可以看出,有很多重复的代码。第二种方法返回强类型视图模型,而第一种方法返回一个对象,因为包含了两个额外的属性(language_group和culture)。

第二种方法用于填充MVC视图,第二种方法用于导出到Excel函数。 重新考虑这一点以减少重复的最佳方法是什么?

3 个答案:

答案 0 :(得分:3)

我会创建一个DTO类,并在其上有一个setter方法,它接受一个I​​Queryable centreTranslation。然后将对象传递给类并在该类中设置所有这些值,并将dto传递回原来的那个方法。

    public class SomeDto
    {
        //All of the properties your setting in the other method

        public void SetDto(IQueryable<CentreTranslation> centreTranslation)
        {
            //call methods that set all the properties
        }

        private SetAddress(IQueryable<CentreTranslation> centreTranslation)
        {
            //set only address properties
        }

我还会为类型创建较小的setter方法,例如与地址有关的所有内容,在名为SetAddress的dto对象上创建一个私有方法,然后继续行。

获得DTO对象后,可以使用Automapper等工具直接从DTO对象映射到ViewModel对象。这将为您提供最大的灵活性,以便在整个应用程序中进行更多重构。

 private ViewModel createViewModel(Dto)

 {
     return Mapper.Map(Dto, ViewModel);    
 }

答案 1 :(得分:1)

private IQueryable<object> CreateCentreViewModel(IQueryable<CentreTranslation> centreTranslation)
{
    return centreTranslation.Select(s => new 
    {
        model = new CentreViewModel()
        {
             id = s.Centre.id,
             centreTranslationId = s.id,
             name = s.Centre.name,
             [...]
        }
        language_group = s.Language.language_group,
        culture = s.Language.cuture
     }
}

答案 2 :(得分:1)

在CentreViewModel类中创建一个静态FromCentreTranslation方法,并将所有初始化放在那里:

public class CentreViewModel 
{
   ....
   public static CentreViewModel FromCentreTranslation(CentreTranslation source)
   {
      CentreViewModel result = new CentreViewModel();
      result.id = source.Centre.id,
      result.centreTranslationId = source.id,
      result.name = source.Centre.name,
      ....
      result.businessLoungeAbout = source.ProductTranslations
                        .Where(w => w.Product.id == (int)Products.BusinessLounge)
                        .FirstOrDefault().about,
      result.dayOfficeAbout = source.ProductTranslations
                        .Where(w => w.Product.id == (int)Products.DayOffice)
                        .FirstOrDefault().about
      return result;
   }
}

然后你可以重构原来的两个方法,如:

private IEnumerable<object> CreateCentreViewModelForExport
                                (IQueryable<CentreTranslation> centreTranslation)
{
   return centreTranslation.Select(s => new 
   {
      centreViewModel = CentreViewModel.FromCentreTranslation(s),
      language_group = s.Language.language_group,
      culture = s.Language.cuture
   }
}

private IQueryable<CentreViewModel> CreateCentreViewModel
                                (IQueryable<CentreTranslation> centreTranslation)
{
  return centreTranslation.Select(s => CentreViewModel.FromCentreTranslation(s)),
}