Wednesday, 15 April 2009

Dice Roller using LINQ

For my day job I'm a software developer at a company that produces telephone billing software. It's something I've done in the past, and I was lucky to get another job working in the same field. Having read a few posts about how useful and easy to read LINQ can be, I decided to take a quick look at writing a dice rolling utility using link to perform common dice rolling tasks.

Here is the code...
using System;
using System.Collections.Generic;
using System.Linq;

namespace DiceUtils
{
public static class Dice
{
private readonly static Random random = new Random();

public static int Roll(int sides)
{
return random.Next(sides) + 1;
}

public static IEnumerable<int> Roll(int dice, int sides)
{
return Enumerable.Range(0, dice).Select(x => Roll(sides));
}

public static IEnumerable<int> Roll(int dice, int sides, int keep)
{
return Roll(dice, sides).AsQueryable().OrderByDescending(x => x).Take(keep);
}
}
}

No comments:

Post a comment