I have a 6 x 7 grid for a calendar = 42 DateTimes
. I'm trying to display the displayed month/year at the top of the calendar.
If there are 3 months displayed, I only want to show the name for the middle month (October 2018, for instance). If 2 months are displayed, split the name (October - November 2018). If 2 months are displayed and have different years, append with year on both sides (December 2018 - January 2019).
This is what I have, and it works, but it's in a property that may be "getted" often and I want this to be as efficient as possible. Here's the code:
public string ViewedMonthYearStr
{
get
{
if (_grid != null)
{
string first;
string middle = string.Empty;
string last = string.Empty;
HashSet<int> months = new HashSet<int> { _grid[0].Month, _grid[21].Month, _grid[41].Month };
if (months.Count == 3) first = _grid[21].ToString("MMMM yyyy");
else
{
first = _grid[0].ToString("MMMM");
middle = " - ";
last = _grid[41].ToString("MMMM yyyy");
}
if (_grid[0].Year != _grid[41].Year && months.Count != 3)
{
middle = $" {_grid[0].ToString("yyyy")} - ";
}
_viewedMonthYearStr = $"{first}{middle}{last}";
}
return _viewedMonthYearStr;
}
}
Is there a more efficient way to do this? My gut tells me that if/else's aren't the most efficient way.
wpf
tag tells me that this property is likely bound to by a calendar view, and those magic values are used to get the first, middle and last date that are displayed. \$\endgroup\$