21. January 2009 14:39
/
0
/
Comments (0)
I was in need of a CreateRange method, similar to the Enumerable.Range(1, 10), that return an Enumerable of Dates. Doing a search I stumble along this blog post, which contains a generic CreateRange method. I then went ahead and converted the code to use extensions. Here’s the end result:
1: public static IEnumerable<t> CreateRange<t>(this t sender, t end, Func<t, t> func) where t : IComparable
2: {
3: if (sender.CompareTo(end) == -1)
4: {//End is greater than start
5: for (t i = sender; (sender.CompareTo(i) != 1) && (end.CompareTo(i) != -1); i = func(i))
6: yield return i;
7: }
8: else
9: {//end is less than or equal to start
10: for (t i = sender; (sender.CompareTo(i) != -1) && (end.CompareTo(i) != 1); i = func(i))
11: yield return i;
12: }
13: }
1: <System.Runtime.CompilerServices.Extension> _
2: Public Shared Function CreateRange(Of t As IComparable)(ByVal sender As t, ByVal [end] As t, ByVal func As Func(Of t, t)) As IEnumerable(Of t)
3: If sender.CompareTo([end]) = -1 Then
4: 'End is greater than start
5: Dim i As t = sender
6: While (sender.CompareTo(i) <> 1) AndAlso ([end].CompareTo(i) <> -1)
7:
8: i = func(i)
9: End While
10: Else
11: 'end is less than or equal to start
12: Dim i As t = sender
13: While (sender.CompareTo(i) <> -1) AndAlso ([end].CompareTo(i) <> 1)
14:
15: i = func(i)
16: End While
17: End If
18: End Function
and you call the method like this:
1: int i = 0;
2: double f = 0.0;
3: DateTime[] dates = dateFrom.CreateRange(dateTo, x1 => x1.AddDays(1)).ToArray();
4: int[] b = i.CreateRange(5, x1 => x1 = x1 + 1).ToArray();
5: double[] d = f.CreateRange(0.9, x1 => x1 = x1 + 0.1).ToArray();
6: string[] c = "a".CreateRange("z", x1 => ((char)((int)x1.ToCharArray()[0] + 1)).ToString()).ToArray();
or you can just set the variables as Enumerable<t> and then deal with them however you like.
Please note this implementation does not work with Chars
Happy Programming!
08c9d327-5272-4731-9751-2388d4a76464|0|.0|27604f05-86ad-47ef-9e05-950bb762570c