好吧,你需要一些更好的null checking和一些更谨慎的代码在这里。
if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{
if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
{
// execute code here
}
}
是不可接受的。
首先,让我们空检查
if (array != null)
{
if (array.Element != null)
为简单起见,你可以使用&&
if (array != null && array.Element != null)
话,里面的是,如果我们使用一个for循环(since you're stuck on arrays)和NULL检查
for (int i = 0; i < array.Element; ++i)
{
if (array.Element[i] != null && array.Element[i].Object != null)
{
那么,既然你有嵌套数组,我们循环再次。这被称为nested loop,这通常是不好的做法,我会告诉你为什么它在一秒钟内工作。
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
现在,所有这种丑陋的嵌套loopyness,我们发现你的物品不是空的。 最重要的是,您可以在这里访问所有潜在的值,并且可以按照自己的喜好进行分组。以下是我如何将整个事情放在一起以简化。
List<string> arrayValues = new List<string>();
if (array != null && array.Element != null)
{
for (int i = 0; i < array.Element.length; ++i)
{
//bool found = false;
if (array.Element[i] != null && array.Element[i].Object != null)
{
for (int o = 0; o < array.Element[i].Object.length; ++o)
{
if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
{
arrayValues.Add(array.Element[i].Object[o].Item);
//if you want to drop out here, you put a boolean in the bottom loop and break and then break out of the bottom loop if true
//found = true;
//break;
}
}
}
//if (found)
// break;
}
}
if (arrayValues.Count > 0)
{
//do stuff with arrayValues
}
为什么不使用'名单',而不是一个数组? –
2012-04-11 20:48:07
第一行中的两个条件是相同的 - 大概这不是故意的? – 2012-04-11 20:48:07
我道歉,应该有两个不同的条件,我改变了它。 – Victor 2012-04-11 20:49:43