Skip to content

Instantly share code, notes, and snippets.

@agross
Created June 22, 2010 13:53
Show Gist options
  • Save agross/448485 to your computer and use it in GitHub Desktop.
Save agross/448485 to your computer and use it in GitHub Desktop.
public class EmailPreferencesLookup
{
public IEnumerable<NicknameToEmail> NicknamesToEmail { get; set; }
public IEnumerable<FullNameToEmail> FullNamesToEmail { get; set; }
public IEnumerable<EmailToEmailPreferences> EmailToPreferences { get; set; }
public Maybe<EmailPreferences> GetPreferencesFor(string fullNameOrEmail)
{
var maybeNick = NicknamesToEmail.TryFind(
x => x.Nickname == fullNameOrEmail,
x => x.Email);
var maybeFullName = FullNamesToEmail.TryFind(
x => x.FullName == fullNameOrEmail,
x => x.Email);
return
from email in maybeNick.Concat(maybeFullName)
from prefs in EmailToPreferences.TryFind(
x => x.Email == email,
x => x.EmailPreferences).Value
select prefs;
}
}
internal static class EnumerableExtensions
{
public static Lazy<Maybe<TResult>> TryFind<T, TResult>(
this IEnumerable<T> instance, Func<T, bool> predicate, Func<T, TResult> resultSelector)
where T : class
{
if (instance == null)
{
return new Lazy<Maybe<TResult>>(() => Maybe<TResult>.None);
}
var found = instance.FirstOrDefault(predicate);
return found != null
? new Lazy<Maybe<TResult>>(() => Maybe.From(resultSelector(found)))
: new Lazy<Maybe<TResult>>(() => Maybe<TResult>.None);
}
public static Maybe<T> Concat<T>(this Lazy<Maybe<T>> source1, Lazy<Maybe<T>> source2)
{
return source1.Value.IsNone
? source2.Value
: source1.Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment