Created
June 28, 2011 09:01
-
-
Save hodzanassredin/1050769 to your computer and use it in GitHub Desktop.
List Extensins Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System; | |
using System.Linq; | |
namespace ConsoleApplication2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var e = 1.To(5).Step(2); | |
var l = new List<int>(); | |
1.To(5).Step(2).ForEach(x => l.Add(x)); | |
var l2 = 1.To(5).Step(2).ToList(); | |
} | |
} | |
public static class Exts | |
{ | |
public static IEnumerable<int> To(this int from, int to) | |
{ | |
if (from < to) | |
{ | |
while (from <= to) | |
{ | |
yield return from++; | |
} | |
} | |
else | |
{ | |
while (from >= to) | |
{ | |
yield return from--; | |
} | |
} | |
} | |
public static IEnumerable<T> Step<T>(this IEnumerable<T> source, int step) | |
{ | |
if (step == 0) | |
{ | |
throw new ArgumentOutOfRangeException("step", "Param cannot be zero."); | |
} | |
return source.Where((x, i) => (i % step) == 0); | |
} | |
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action) | |
{ | |
foreach (T item in enumeration) | |
{ | |
action(item); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment