以下功能可以改进吗?(C#3.0)

New*_*bie 0 c#-3.0

我有以下功能

public static List<DateTime> GetOnlyFridays(DateTime endDate, int weeks, bool isIncludeBaseDate)
{
    //Get only the fridays from the date range
    List<DateTime> dtlist = new List<DateTime>();

    List<DateTime> tempDtlist = (from dtFridays in GetDates(endDate, weeks)
                                 where dtFridays.DayOfWeek == DayOfWeek.Friday
                                 select dtFridays).ToList();

    if (isIncludeBaseDate)
    {
        dtlist = tempDtlist.Skip(1).ToList();
        dtlist.Add(endDate);
    }
    else
    {
        dtlist = tempDtlist;
    }

    return dtlist;
}
Run Code Online (Sandbox Code Playgroud)

基本上我正在做的是使用GetDates函数获取日期列表,然后根据isIncludeBaseDate bool value(如果为真)跳过最后一个日期并添加Base Date

它工作正常,但这个程序可以改进吗?

我正在使用C#3.0和Framework 3.5

谢谢

tza*_*man 6

你做了太多的临时列表转换; 您可以将所有工作作为查询保留到最后,这样它只会被评估一次.

public static List<DateTime> GetOnlyFridays(DateTime endDate, int weeks, bool isIncludeBaseDate)
{
    var fridays = GetDates(endDate, weeks)
                    .Where(d => d.DayOfWeek == DayOfWeek.Friday);
    if (isIncludeBaseDate)
    {
        fridays = fridays.Skip(1)
                         .Concat(new []{endDate});
    }
    return fridays.ToList();
}
Run Code Online (Sandbox Code Playgroud)