patterncsharpMinor
Return a key when a function returns true
Viewed 0 times
returnfunctiontruereturnswhenkey
Problem
I've no idea what to call this, so I called it
Basically, the idea is to pass a
The intention is to make this a generic extension method.
Pretty simple, but pretty useful (for me at least) as well.
Usage:
Classify since that's how I use it.Basically, the idea is to pass a
Dictionary> which is evaluated for an input, and the first Func returning true will return the TResult key.The intention is to make this a generic extension method.
public TResult Classify(TValue input, Dictionary> classifications)
{
foreach (var classification in classifications)
{
if (classification.Value.Invoke(input))
{
return classification.Key;
}
}
return default(TResult);
}Pretty simple, but pretty useful (for me at least) as well.
Usage:
> { ["good"] = x => x >= 3, ["neutral"] = x => x > 2, ["bad"] = x => true }) %>'>
Solution
Needs more LINQ:
This has the advantage (IMO) of highlighting the fact that you're discarding all but the first match (note that iteration order is not guaranteed!).
A generic extension method seems like a good idea - call your source
That one-liner makes use of the fact that
return classifications.FirstOrDefault(item => item.Value.Invoke(input)).Key;This has the advantage (IMO) of highlighting the fact that you're discarding all but the first match (note that iteration order is not guaranteed!).
Classify doesn't really convey the fact that you're returning a Key from a dictionary. Seems FindKey would be a much better name.A generic extension method seems like a good idea - call your source
source, and stick to TKey and TValue:public static TKey FindKey(this IDictionary> source, TValue input)
{
return source.FirstOrDefault(item => item.Value.Invoke(input)).Key;
}That one-liner makes use of the fact that
KeyValuePair is a struct (and therefore can't be null), so you can just return .Key and that will be default(TKey).Code Snippets
return classifications.FirstOrDefault(item => item.Value.Invoke(input)).Key;public static TKey FindKey<TKey, TValue>(this IDictionary<TKey, Func<TValue, bool>> source, TValue input)
{
return source.FirstOrDefault(item => item.Value.Invoke(input)).Key;
}Context
StackExchange Code Review Q#139178, answer score: 8
Revisions (0)
No revisions yet.