繁体   English   中英

如何将一组<=,> = if ... else语句重构为字典或类似的东西

[英]how to refactor a set of <= , >= if…else statements into a dictionary or something like that

有一个方法接收一个int参数,并通过一组if ... else语句检查参数来返回一个字符串:

if(param == 1)
{
    return "1";
}
else if(param ==20)
{
    return "20";
}
else
{
    if(param <= 10)
    {
        return "below 10";
    }
    else if(param <= 30 )
    {
        return "below 30";
    }
    ...
}

我想知道是否可以将这些“> =,<=”条件放在字典中

您可以使用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不保证项目的顺序, KeyValuePair List应该是最好的情况:

    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;
    }

例如,可以使用字典。

只是伪代码的一个例子:

var dic = new Dictionary<int,string>{{1,"1"}, {20, "20"}...}

而是长期if

string value = null; 
dic.TryGetValue(param, out value);

您的操作不适合字典。 考虑以下两种情况

param == 29 and param ==28

两者都会输出“低于30”。 如果param变量的范围很大,那么你必须在字典中手动放入所有可能的值和相应的输出字符串。 这似乎是个好主意???

不,字典不是为此而设计的。 如果您确实有太多的比较条件,您可以将比较器放在数组或列表中,将值放在另一个数组/列表中的相应顺序,然后使用binarysearch查找键的索引,并使用索引获取值。 这是一个例子:

    static string find(int val)
    {
        int[] keys = {30,40,50};
        string[] messages = {"Below 30","Below 40","Below 50"};
        int idx = Array.BinarySearch(keys,val);
        if(idx < 0)idx = ~idx;
        return idx < 3 ? messages[idx] : "Off the chart!";
    }

    public static void Main (string[] args)
    {
        Console.WriteLine (find(28));
        Console.WriteLine (find(50));
        Console.WriteLine (find(100));
    }

我厌倦了以下。 如果您遇到任何问题,请告诉我们:

            int testInput = 15;

            Func<int, bool> delegateForCondition1 = param => param == 1;
            var conditionsSet = new HashSet<KeyValuePair<Func<int, bool>, String>> 
                        { 
                          new KeyValuePair<Func<int, bool>, String>(delegateForCondition1, "It is 1"), 
                          new KeyValuePair<Func<int, bool>, String>(param => param <= 10 , "below 10"),
                          new KeyValuePair<Func<int, bool>, String>(param => param <= 30 , "below 30")
                        };


            foreach (KeyValuePair<Func<int, bool>, String> pair in conditionsSet)
            {
                Func<int, bool> currentKeyAsDelegate = pair.Key;
                bool currentResult = pair.Key(testInput);
                Console.WriteLine(currentKeyAsDelegate + "---" + currentResult);
            }

            //Select the first matching condition
            KeyValuePair<Func<int, bool>, String> selectedPair = conditionsSet.FirstOrDefault(p => p.Key(testInput));
            if (selectedPair.Key != null)
            {
                Console.WriteLine(selectedPair.Value);
            }


            Console.ReadLine();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM