Don't do what I did and implement an Expression Tree Visitor by hand. I was creating an application that used LINQ to SQL to connect to a database, but I wanted to customise the generated SQL queries. Use this very useful bit of code provided on the MSDN website:
http://msdn.microsoft.com/en-us/library/bb882521.aspx
Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts
Thursday, 7 May 2009
Friday, 1 May 2009
Perform an Action for each value in a Collection
I really don't know why there is no
To solve this issue just create a new extension method that wraps the call
ForEach
method in LINQ. If you want to perform an action on every item in a collection you have to use the TAccumulate Aggregate<TSource, TAccumulate>(TAccumulate, Func<TAccumulate, TSource TAccumulate>)
method in order to avoid deferred execution, but calling it with a simple action leads to unnecessary ugly and hard to understand code.To solve this issue just create a new extension method that wraps the call
Aggregate
call:public static class IEnumerableExtensions
{
public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
{
source.Aggregate<TSource, object>(null, (dummy, item) => { action(item); return null; });
}
}
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...
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);
}
}
}
Subscribe to:
Posts (Atom)