Archive for the ‘csharp’ Category

Little Red Riding Hood – In C#

Tonight, I was bored. Seriously, it was either this or watching the Eurovision song contest. Sadly, with BBC iPlayer, I was able to do both.

I’ve decided that when I have kids, they’re going to know how to use computers and learn how to program (I can wish).

So, I’ve rewritten the story of Little Red Riding Hood. This time it’s in C#. I have no idea why I decided I would do this – by the time I’d realised, it was too late

So if you want to tell your kids a bedtime story whilst edging them into becoming programmers, read on.

Read More

Getting a list of numbers between two values

This is yet another extension.

I don’t like Enumerable.Range() for the sole reason you have to give a start index and a count. So I made up my own. This is an extension for an integer type and will allow you to specify two values that you want a range for

public static IEnumerable<int> RangeTo(this int startValue, int endValue, int step)
{
	return (endValue < startValue) ?
		Enumerable.Range(endValue, startValue - endValue + 1).Reverse() :
		Enumerable.Range(startValue, endValue - startValue + 1);
}

This will also allow for reverse lists – see how to use it below:

1.RangeTo(10);  // {1,2,3,4,5,6,7,8,9,10}
5.RangeTo(10);  // {5,6,7,8,9,10}
10.RangeTo(5);  // {10,9,8,7,6,5}
3.RangeTo(3);   // {3}

int x = 15;
int y = 17;
x.RangeTo(10);  // {15,14,13,12,11,10}
y.RangeTo(x);  // {17,16,15}
x.RangeTo(y);  // {15,16,17}
13.RangeTo(x); // {13,14,15}

Random sort on IEnumerable object

Quick extension on an IEnumerable object to return the collection in a random order:

public static IEnumerable<T> Random<T>(this IEnumerable<T> source)
{
	return source.OrderBy(x => Guid.NewGuid());
}

For example, to return a random set of 5 items from the collection:

var randomSet = myEnumerable.Random().Take(5);

If anyone knows of a better way, let me know :)