Warm tip: This article is reproduced from stackoverflow.com, please click
c# iterator yield-return

Can this function be written in more efficient way?

发布于 2020-03-29 21:01:38

I am just getting the days of the week back from the function. If it is a holiday week then just adding word 'holiday' after each day.

    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;
    }

so can this be written in a more efficient way? Perhaps using yield return?

Questioner
Haseeb Sd
Viewed
19
Pavel Anikhouski 2020-02-01 19:36

You can use Select method from System.Linq to simplify your code and return a day names with Holiday added (when isHolidayWeek equals true). Moving the Days collection outside the method can also help to minimize a memory consumption (at little bit)

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;
}