Created
June 22, 2010 13:53
-
-
Save agross/448485 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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