Why is this code throwing an InvalidOperationException?

前端 未结 2 2084
孤独总比滥情好
孤独总比滥情好 2021-02-14 16:06

I think that my code should make the ViewBag.test property equal to \"No Match\", but instead it throws an InvalidOperationException.

相关标签:
2条回答
  • 2021-02-14 16:40

    As you can see here, the First method throws an InvalidOperationException when the sequence on which it is called is empty. Since no element of the result of the split equals Hello5, the result is an empty list. Using First on that list will throw the exception.

    Consider using FirstOrDefault, instead (documented here), which, instead of throwing an exception when the sequence is empty, returns the default value for the type of the enumerable. In that case, the result of the call will be null, and you should check for that in the rest of the code.

    It might be cleaner still to use the Any Linq method (documented here), which returns a bool.

    string str = "Hello1,Hello,Hello2";
    string another = "Hello5";
    bool retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                       .Any(p => p.Equals(another));
    if (retVal)
    {
       ViewBag.test = "Match";
    }
    else
    {
       ViewBag.test = "No Match"; //not work
    }
    

    And now the obligatory one liner using the ternary operator:

    string str = "Hello1,Hello,Hello2";
    string another = "Hello5";
    ViewBag.test = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                       .Any(p => p == another) ? "Match" : "No Match";
    

    Note that I also used == here to compare strings, which is considered more idiomatic in C#.

    0 讨论(0)
  • 2021-02-14 16:58

    Give this a shot:

    bool hasMatch = str.Split(',').Any(x => x.Equals(another));
    
    ViewBag.test = hasMatch ? "Match" : "No Match";
    
    0 讨论(0)
提交回复
热议问题