c# - Why is this code throwing an InvalidOperationException? -
i think code should make viewbag.test
property equal "no match"
, instead throws invalidoperationexception
.
why this?
string str = "hello1,hello,hello2"; string = "hello5"; string retval = str.split(",".tochararray(), stringsplitoptions.removeemptyentries) .first(p => p.equals(another)); if (str == another) { viewbag.test = "match"; } else { viewbag.test = "no match"; //this not happen when should }
as can see here, first
method throws invalidoperationexception
when sequence on called empty. since no element of result of split equals hello5
, result empty list. using first
on list throw exception.
consider using firstordefault
, instead (documented here), which, instead of throwing exception when sequence empty, returns default value type of enumerable. in case, result of call null
, , should check in rest of code.
it might cleaner still use any
linq method (documented here), returns bool
.
string str = "hello1,hello,hello2"; string = "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 obligatory 1 liner using ternary operator:
string str = "hello1,hello,hello2"; string = "hello5"; viewbag.test = str.split(",".tochararray(), stringsplitoptions.removeemptyentries) .any(p => p == another) ? "match" : "no match";
note used ==
here compare strings, considered more idiomatic in c#.
Comments
Post a Comment