C#从两个返回表达式的方法中排除重复代码

时间:2017-11-04 14:35:01

标签: c# .net asp.net-mvc linq asp.net-core

我有两个函数,将表达式转换为EF。:

 public static Expression<Func<TripLanguage, TripViewModel>> ToSearchModel(ILookup<int, TagViewModel> tags)
    {            
        return tripLanguage => new TripViewModel()
        {
            From = tripLanguage.From,
            To = tripLanguage.To,
            Annotation = tripLanguage.Description.Truncate(Strings.TRUNCATE_ANOTATION),
            Level = tripLanguage.Trip.Level,
            BicycleType = tripLanguage.Trip.BicycleType,
            UrlId = tripLanguage.UrlId,
            Distance = tripLanguage.Trip.Distance,
            Tags = tags[tripLanguage.TripId], //This is only different and in function args of course
            MainImage = tripLanguage.Trip.Images.OrderBy(s => s.Date).Select(i => new ImageViewModel
            {
                Filename = i.Filename,
                Id = i.Id,
                Title = i.Title
            }).Take(1)
        };
    }

    public static Expression<Func<TripLanguage, TripViewModel>> ToSearchModel()
    {
        return tripLanguage => new TripViewModel()
        {
            From = tripLanguage.From,
            To = tripLanguage.To,
            Annotation = tripLanguage.Description.Truncate(Strings.TRUNCATE_ANOTATION),
            Level = tripLanguage.Trip.Level,
            BicycleType = tripLanguage.Trip.BicycleType,
            UrlId = tripLanguage.UrlId,
            Distance = tripLanguage.Trip.Distance,                
            MainImage = tripLanguage.Trip.Images.OrderBy(s => s.Date).Select(i => new ImageViewModel
            {
                Filename = i.Filename,
                Id = i.Id,
                Title = i.Title
            }).Take(1)
        };
    }

唯一不同的是Tags集合。有可能像调用方法,没有参数和添加标签属性,排除重复的代码?或者使用一些继承表达式?

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

更改第一种方法以使用null标记,并为其提供null默认值:

public static Expression<Func<TripLanguage,TripViewModel>> ToSearchModel(ILookup<int, TagViewModel> tags = null) {
    return tripLanguage => new TripViewModel() {
        From = tripLanguage.From,
        To = tripLanguage.To,
        Annotation = tripLanguage.Description.Truncate(Strings.TRUNCATE_ANOTATION),
        Level = tripLanguage.Trip.Level,
        BicycleType = tripLanguage.Trip.BicycleType,
        UrlId = tripLanguage.UrlId,
        Distance = tripLanguage.Trip.Distance,
        Tags = tags?[tripLanguage.TripId], // <<== Note the question mark
        MainImage = tripLanguage.Trip.Images.OrderBy(s => s.Date).Select(i => new ImageViewModel
        {
            Filename = i.Filename,
            Id = i.Id,
            Title = i.Title
        }).Take(1)
    };
}