您可以使用Dictionary<Func<int, bool>, string>
:
private string Do(int input)
{
var dic = new Dictionary<Func<int, bool>, string>
{
{param => param == 1, "1"},
{param => param == 20, "20"},
{param => param <= 10, "below 10"},
{param => param <= 30, "blow 30"}
};
return dic.First(pair => pair.Key(input)).Value;
}
编辑:
@Maarten 的评论是正确的,Dictionary
不保证项目的顺序,在这种情况List
下KeyValuePair
应该是最好的:
private string Do(int input)
{
var pairs = new List<KeyValuePair<Func<int, bool>, string>>
{
{param => param == 1, "1"},
{param => param == 20, "20"},
{param => param <= 10, "below 10"},
{param => param <= 30, "blow 30"}
};
var pair = pairs.FirstOrDefault(pair => pair.Key(input));
if (pair == null) return string.Empty; // return whatever you want
return pair.Value;
}