从字典中提取信息... if / else语句的替代方法

时间:2018-11-29 15:30:51

标签: c# data-structures

我有一本看起来像这样的字典:

Dictionary<string, DateTime> Seasons = new Dictionary<string, DateTime>
{
    { "WINTER_START", Date1},
    { "WINTER_END", Date2 },
    { "SUMMER_START", Date3 },
    { "SUMMER_END", Date4 }
};

假设我有今天的日期var today = DateTime.Today.Date,我想知道今天的日期是冬季还是夏季。我已经使用If / Else语句完成了此操作,但是我内在的某些事情告诉我,还有一种更好的方法。

string currentSeason = "";

if (today >= Seasons["WINTER_START"] && today <= Seasons["WINTER_END"])
{
    currentSeason = "WINTER";
} 
else if (today >= Seasons["SUMMER_START"] && today <= Seasons["SUMMER_END"])
{
    currentSeason = "SUMMER";
}

1 个答案:

答案 0 :(得分:2)

不知道您是否已为此使用字典,但是我认为这是一个更友好的版本,以及我将如何解决该问题:

void Main()
{
    var seasons = new List<Season>
    {
        new Season("Winter", Date1, Date2),
        new Season("Summer", Date3, Date4)
    };

    var today = DateTime.Today;

    // null if no matching season was found
    string currentSeason = seasons.FirstOrDefault(season => season.InSeason(today))?.Name;
}

public class Season
{
    public Season(string name, DateTime start, DateTime end)
    {
        Name = name;
        Start = start;
        End = end;
    }

    public string Name { get; set; }

    public DateTime Start { get; set; }
    public DateTime End { get; set; }

    public bool InSeason(DateTime input)
    {
        return input >= Start && input <= End;
    }
}

还有一个小小的注释:Current_Season对于局部变量来说不是一个好的变量名。 This可能会帮助您改善命名。