返回从List <string>

时间:2017-12-01 11:49:36

标签: c#

要求新手能够了解这个案例。如果我有多个单词匹配,会怎么样?例如,给出另一个与单词列表匹配的单词。如果我通过getvalue(&#34; paddy&#34;)应该得到100.同样,从List匹配的任何单词都应返回100。 谢谢你的时间。

   Console.WriteLine(getvalue("sam"));      


    public static int getvalue (string c)
    {
       //here would be creating a list
       List<string> wordlist = new List<string> { "sam", "paddy", "murphy",
                                              "saint"};
      string s;
      if(wordlist.Any(c.Contains))
      {
        s = c;
        Console.WriteLine("found word" + s);
      }
        //this should be matching the object found word
        return c == "sam" ? 100 : -10;

     }

3 个答案:

答案 0 :(得分:2)

你在寻找类似的东西;

        if (wordlist.Any(c.Contains))
        {
            Console.WriteLine("found word" + s);
            return 100;
        }
        return -10;

答案 1 :(得分:2)

如果你想在你的单词的单词或任何子字符串在你的列表中时返回100,而当它不在你的单词或任何子字符串时返回-10,那么以下内容将起作用:

public static int getvalue (string c)
{
    List<string> wordlist = new List<string> { "sam", "paddy", "murphy", "saint"};
    return wordlist.Any(c.Contains) ? 100 : -10;
}

应该注意c.Contains将检查列表中的单词是否是输入值的子字符串。所以以下将全部返回100:萨曼莎,样品,香醋。如果这不是想要的,你想要完全匹配只考虑这个:

public static int getvalue (string c)
{
    List<string> wordlist = new List<string> { "sam", "paddy", "murphy", "saint"};
    return wordlist.Contains(c) ? 100 : -10;
}

对于sam,paddy等,这将返回100,对于萨曼莎,样品,香醋,这将返回-10。

我还要注意,代码约定意味着您应该为参数指定比c更好的名称,并且方法名称应为GetValuehttps://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions是一个很好的起点。

答案 2 :(得分:0)

传入一个数组或字符串列表以匹配,这将使检查和返回结果变得更加简单。

Rainman的回答也适用于你想要的结果。

相关问题