温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Can this function be written in more efficient way?

c# - 可以用更有效的方式编写此函数吗?

发布于 2020-03-29 21:48:58

我只是从功能中返回星期几。如果是假期周,则在每天之后添加单词“ holiday”。

    public IEnumerable<string> GetDays(bool isHolidayWeek)
    {
        var days= new List<string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
        var i = 0;
        if (isHolidayWeek)
            foreach (var day in days)
                days[i++] = day + " Holiday";

        return days;
    }

这样可以更有效地编写吗?也许使用收益率回报?

查看更多

提问者
Haseeb Sd
被浏览
11
Pavel Anikhouski 2020-02-01 19:36

您可以使用Selectfrom方法System.Linq来简化代码,并返回带有Holiday添加的日期名称isHolidayWeek等于时true)。Days集合移到该方法之外还可以帮助最小化内存消耗(一点点)

public static readonly IList<string> Days = new List<string>()
    {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

public static IEnumerable<string> GetDays(bool isHolidayWeek)
{
    if (isHolidayWeek)
        return Days.Select(d => $"{d} Holiday");
    return Days;
}

发布
问题

分享
好友

手机
浏览

扫码手机浏览