Wednesday, November 28, 2007

Quick Tip - Read Only Automatic Properties

This is a simple little trick, which I only discovered a few weeks ago.

In the past providing public "read only" access to a member would look something like:
private string connection;

public string Connection
get { return connection; }

With Automatic Properties in C# 3.5 the code becomes:
public string Connection { get; private set; }

The neat trick is the access modifier (private) next to the set. This allow you to internally modify the member, while publicly providing "read only" access.

Monday, November 26, 2007

VS2008 RTM Update

I have updated all the downloadable code to compile with the RTM release of VS2008.

It's not a big change, so I'll use this blog entry to update my Xceed <-> Linq code. I've fixed some minor bugs, improved performance a lot and added better linq syntax support.

So if you're using the code, it'd be a good idea to update.

Monday, November 19, 2007

IEnumerable Joy - Batch / Split

I was inspired by my good friend Nick's latest blog entry Return of the Batch Enumerable

Here he demonstrates a neat idea of using extension methods and yield to split an IEnumerable into arbitrary batches.

My version is slightly less efficient, but treats the batches as separate lazy collections - so you can use it on multiple threads etc.

I've also added a Split extension, which I'll describe - but first, the code!

static class InBatchesExtension
public static IEnumerable<IEnumerable<T>> InBatches<T>(this IEnumerable<T> source, int batchSize)
for (IEnumerable<T> s = source; s.Any(); s = s.Skip(batchSize))
yield return s.Take(batchSize);

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int items)
for (int i = 0; i < items; ++i)
yield return source.Where((x, index) => (index % items) == i);

The InBatches returns the same output as Nicks:

Batch: 1 2 3
Batch: 4 5 6
Batch: 7

And the Split batches the output across the collections:

Batch: 1 4 7
Batch: 2 5
Batch: 3 6

So this gives you 2 different batch splitting methods for a generic enumerable.

I love this stuff.

Tuesday, November 13, 2007

Wield the Yield

Recently I've noticed an IO pattern emerging combining yield and linq; a powerful and efficient mechanism to read data.

Check the following code: We safely open a file (with the using statement), and yield the results with a loop.
IEnumerable<string> ReadFile(string filename)
using (StreamReader reader = new StreamReader(File.OpenRead(filename)))
while (reader.EndOfStream == false)
yield return reader.ReadLine();

This simple (and beautiful) code allows us to treat a file like an array of strings - which becomes very powerful when coupled with linq.
// Contrived example - How many file lines refer to "fred"?
var result = ReadFile("file.txt").Where(x => x.Contains("fred")).Count();

I'm sure this same pattern could also be applied to other data retrieval methods, eg algorithm calculation (prime numbers, Fibonacci, etc), network communication (message queue) and even as an abstraction over asynchronous data methods.

Yield provides a lazy enumeration (doesn't execute unless needed) so the solution is generic and efficient - I like it.

Monday, November 5, 2007

n! - let me count the ways

The other day I had an interesting discrete maths assignment question involving permutations - so I decided to codify it.

"How many ways can six people (Josh, Toby, CJ, Sam, Leo & Donna) sit, if Josh must sit to the left of Leo and to the right of Sam."

Now the astute reader will immediately recognize the answer to be 2 * (4! + 3!3!) = 120; but to be sure I wanted to double check this via C#. (I'm keen to redo this in F# too)

My solution was a quick hack, and is by no means "the best way" - but using linq it sure looks pretty.

class Program
static IEnumerable<List<string>> Permutate(IEnumerable<string> people,
IEnumerable<string> current)
// Get remaining people and recurse
foreach (var person in people.Where(x => current.Contains(x) == false))
foreach (var result in Permutate(people, current.Concat(new string[] { person })))
yield return result;

if (current.Count() == people.Count())
yield return current.ToList();

static void Main(string[] args)
string[] people = new string[] { "Josh", "Toby", "CJ", "Sam", "Leo", "Donna" };

var result = Permutate(people, new string[] { }).ToList();

// Josh sits to the left of Leo
var Josh_Leo = result.Where(r =>
r.FindIndex(x => x == "Josh") < r.FindIndex(x => x == "Leo"));

// Josh sits to the right of Sam
var Sam_Josh = Josh_Leo.Where(r =>
r.FindIndex(x => x == "Sam") < r.FindIndex(x => x == "Josh"));

var count = Sam_Josh.Count();

This simple example shows why I'm a such fan of linq in C# - the pre-linq code for this certainly wouldn't be as eloquent.

Oh, and it also shows why I'm a fan of maths... it's much more efficient to just to calculate the factorials.

Update: Formatting code in a blog sure is a pain!