简体   繁体   English

检查数组成员是否存在

[英]check if array member exist

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". 现在这个构造给出了comppiler错误:“无法将字符串转换为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]. ;-)我需要检查“msg”数组的任意元素是否存在,而不仅仅是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] [/编辑]

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

Unlike Javascript, C# does not allow you to use arbitrary expressions as booleans. 与Javascript不同,C#不允许您将任意表达式用作布尔值。

You're trying to write 你正在努力写作

msg.Length >= 3 ? msg[2] : "Failed"

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

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