Skip to content

Instantly share code, notes, and snippets.

@lucasmeijer
Created January 9, 2015 09:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lucasmeijer/e7bb3a981c2b2887642d to your computer and use it in GitHub Desktop.
Save lucasmeijer/e7bb3a981c2b2887642d to your computer and use it in GitHub Desktop.
Can you write a better version?
using System;
using System.Collections.Generic;
using System.Linq;
class Experiment
{
//ErrorsFor takes a hayStack, a bunch of needles, and is supposed to invoke errorMessage generator for everything
//in the haystack that matches a certain needle. As an excersice, i've been trying out all the different ways
//to write it, and evaluate for clarity, conciceness, readability by others, readability by me.
//
//Please comment with which version you think has the best balance of all the properties described below,
//and feel free to add improved versions.
IEnumerable<string> ErrorsFor0(string[] hayStack, string[] needles, Func<string, string, string> errorMessageGenerator)
{
foreach (var hay in hayStack)
{
string matchingNeedle = null;
foreach(var needle in needles)
if (hay.Contains(needle))
matchingNeedle = needle;
if (matchingNeedle == null)
continue;
yield return errorMessageGenerator(hay, matchingNeedle);
}
}
IEnumerable<string> ErrorsFor1(string[] hayStack, string[] needles, Func<string, string, string> errorMessageGenerator)
{
foreach (var hay in hayStack)
{
var matchingNeedle = needles.FirstOrDefault(hay.Contains);
if (matchingNeedle == null)
continue;
yield return errorMessageGenerator(hay, matchingNeedle);
}
}
IEnumerable<string> ErrorsFor2(string[] hayStack, string[] needles, Func<string, string, string> errorMessageGenerator)
{
return hayStack.Select(hay => new {hay, matchingNeedle = needles.FirstOrDefault(hay.Contains)})
.Where(@t => @t.matchingNeedle != null)
.Select(@t => errorMessageGenerator(@t.hay, @t.matchingNeedle));
}
IEnumerable<string> ErrorsFor3(string[] hayStack, string[] needles, Func<string, string, string> errorMessageGenerator)
{
return from hay in hayStack
let matchingNeedle = needles.FirstOrDefault(hay.Contains)
where matchingNeedle != null
select errorMessageGenerator(hay, matchingNeedle);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment