I wrote an extension method that can be applied on a ValueTuple<int,int>
, and is in my opinion the easiest way to use, if your language version already supports them. In your example that would be used like this:
cboYearList.ItemsSource = (DateTime.Today.Year, 1950).EnumerateInclusive().ToList();
cboYearList.ItemsSource = (1950, DateTime.Today.Year).EnumerateInclusive().ToList(); //reverse
I implemented the extension method like this. Just put it in a static class in your namespace.
/// <summary>
/// Enumerates all values between the first and second value in range.
/// Automatically handles the enumeration-direction.
/// </summary>
/// <param name="range">The first parameter specifies the first value of the enumeration,
/// the second parameter specifies the last value of the enumeration.</param>
public static IEnumerable<int> EnumerateInclusive(this (int start, int end) range)
{
if (range.start <= range.end)
for (int i = range.start; i <= range.end; i++)
yield return i;
else
for (int i = range.start; i >= range.end; i--)
yield return i;
}
The name is chosen that it is clear that both, start and end, are included in the enumeration. It has the advantage to support iteration in both directions in contrast to Enumerable.Range
which only iterates ascending. In case you need to target an older Language Version you could easily do without ValueTuples
, but I like this short and concise way without having to remember a class name.