Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if array member exist

Tags:

arrays

c#

All,

Consider following piece of code:

string message = "abc;def;ghi";
string[] msgs = message.Split(';');
string temp = msg[2] ? msg[2] : "Failed";

Message variable is coming from the server and has different length. I need to parse it so that if the value does not exist, result should be "Failed".

Is there an easy way to do that?

Right now this construct gives comppiler error: "Cannot convert string to bool".

Thank you.

[EDIT]

I guess some people read this letter by letter. ;-) I need to check if an arbitrary element of the "msg" array exist, not just msg[2]. I can have something like:

string message = "abc;def";
str[] msg = message.Split( ';' );
string temp = msg[3] ? msg[3] : "Failed";

in the next message processing.

[/EDIT]

like image 473
Igor Avatar asked Sep 23 '26 11:09

Igor


2 Answers

Perhaps you wanted:

string temp = msgs.Length > 2 ? msgs[2] : "Failed";

Edit:

For checking any element, the same thing works:

int index = 42;
string temp = msgs.Length > index ? msgs[index] : "Failed";
like image 159
Reed Copsey Avatar answered Sep 25 '26 05:09

Reed Copsey


Unlike Javascript, C# does not allow you to use arbitrary expressions as booleans.

You're trying to write

msg.Length >= 3 ? msg[2] : "Failed"
like image 23
SLaks Avatar answered Sep 25 '26 06:09

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!