Archive for the ‘Linq’ Category

.Net microbenchmarking

06:05 PM

In a recent discussion on StackOverflow about performance of arrays vs. lists and for vs. foreach, Jon Skeet created a little microbenchmarking framework and posted his detailed findings on his blog.

First, my local results of the benchmark. I compiled them as Release under VS 2008 SP1. Running without debugging on a Q6600@2.40GHz, .NET 3.5 SP1. They pretty exactly match Jon’s numbers so I won’t duplicate them here, but you can find them in the page’s source.


============ Doubles ============
============ double[] ============
For 1,00
ForHoistLength 1,00
ForEach 1,00
IEnumerableForEach 8,28
Enumerable.Sum 8,27

============ List ============
For 2,00
ForHoistLength 1,43
ForEach 6,02
IEnumerableForEach 14,03
Enumerable.Sum 14,04

============ Ints ============
============ int[] ============
For 1,00
ForHoistLength 2,06
ForEach 1,38
IEnumerableForEach 15,46
Enumerable.Sum 16,06

============ List ============
For 2,84
ForHoistLength 3,53
ForEach 4,86
IEnumerableForEach 26,33
Enumerable.Sum 26,33

Out of interest how the differences are when there is more to do in the loop’s body, I added a test suite that formatted the sum as string and appended it to a StringBuilder:

(more…)

Dynamic search with Linq

05:50 PM

The Problem: Find all sentences with either “fox” and “dog” and “fox” or “cat”.


string[] sentences = new string[] {
  "The quick brown fox jumps over the lazy dog",
  "The quick brown fox jumps over the lazy cat"};
string[] findAnd = new string[] { "fox", "dog" };
string[] findOr = new string[] { "dog", "cat" };

The first part (find all) is simple:


var queryand = sentences.AsQueryable();
foreach (string find in findAnd)
{
  string f = find;
  queryand = queryand.Where(s => s.Contains(find));
}

Console.WriteLine(string.Join("\n", queryand.ToArray()));

But how to implement to Or part? Well, google is my best friend. I found the following solution:

Predicate Builder on C# 3.5 in a Nutshell

But this solution does not work with Entity Framework: Predicate Builder and Entity Framework on stackoverflow.com

After implementing this solution your code will look like this:


var predicate = Extensions.False<string>();
foreach (string find in findOr)
{
  string f = find;
  predicate = predicate.Or(s => s.Contains(f));
}
var queryor = sentences.AsQueryable().Where(predicate);
Console.WriteLine(string.Join("\n", queryor.ToArray()));

P.S.: You can find an ExpressionVisitor here: ExpressionVisitor at MSDN