好吧,你需要一些更好的空值检查 https://stackoverflow.com/a/4850533/1178921这里还有一些更谨慎的代码。
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)
然后,在 if 内部,我们使用 for 循环 (因为你被困在数组上 https://stackoverflow.com/a/434765/1178921) 和 null 检查它
for (int i = 0; i < array.Element; ++i)
{
if (array.Element[i] != null && array.Element[i].Object != null)
{
然后,由于您有嵌套数组,我们再次循环。这被称为嵌套循环 http://www.techotopia.com/index.php/C_Sharp_Looping_-_The_for_Statement,这通常是不好的做法,我稍后会向您展示为什么它有效。
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))
{
现在,由于所有这些丑陋的嵌套循环,我们发现您的 Item 不为空。
最重要的是,您可以访问此处的所有潜在值,并可以根据需要对它们进行分组。为了简化起见,我将把整个事情放在一起。
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
}