Archive for the ‘C#’ Category

IEnumerable extension to create a delimited string from a string list

With string lists, one thing that I find myself doing a lot is combining the list by some delimiter. In C#, this is a fairly easy thing to do but (today especially) I’ve seen a lot of places where people suggest using a string builder and appending a formatted string (then getting a substring to remove the last delimiter) or something similar. I’m not completely against this, I just think this method is neater:

        public static string ToString<T>(this IEnumerable<T> source, string delimiter)
        {
            return string.Join(delimiter, source);
        }

That will throw up an exception if ‘source’ is null. That’s fine for me, since I don’t want that extension from hiding something that might be wrong elsewhere (i.e. why am I trying to join a null list). If you want to make this work fine and dandy for a null source, you can just use the null coalescing operator and provide an empty source:

        public static string ToString<T>(this IEnumerable<T> source, string delimiter)
        {
            return string.Join(delimiter, source ?? Enumerable.Empty<T>());
        }

Now why do I think this is a better solution that the string builder option? Well, if you whack open Reflector, you’ll notice that the Join method uses a StringBuilder object and builds up from there. So since it’s already built straight into the framework, why reinvent the wheel? Of course, the Join method with an IEnumerable as an argument is only available on .NET 4.0. Anything prior to .NET 4.0 and you’ll have to pass in a string array (at which point the string builder method would be useful).

Another point to notice from the documentation is that the Join method will set the separator to String.Empty, if you pass it a null. The same applies to any element in the list that is null – it is simply replaced by another empty string.

Indexed IEnumerable extension

The original intention for this was to clean up some code which was calling a Select to get an Index value so that basic zebra striping of rows could be done. It return an IndexedType generic class of type T which has properties for the original object and the index value of it.

public static IEnumerable<IndexedType<T>> Index<T>(this IEnumerable<T> source)
{
	return source.Select((x, i) => new IndexedType<T>() { Item = x, Index = i });
}

And the class returned:

public class IndexedType<T>
{
	public T Item { get; set; }
	public int Index { get; set; }
}

This could be extended to include values like if the index value is even, N-Indexed values, etc but I leave that up to the imagination of the programmer.

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 :)