if (text != "" || text != null)
myList[i] = text;
myList是字符串數組 但是,在循環結束時,我一直在myList中看到「」或null的項目。爲什麼我在數組中看到空或「」項?
WindowSnap[] windowsarray = WindowSnap.GetAllWindows(true, true).ToArray();
this.listBoxSnap.BeginUpdate();
this.listBoxSnap.Items.Clear();
this.listBoxSnap.Items.AddRange(windowsarray);
string[] myList = new string[listBoxSnap.Items.Count];
for (int i = listBoxSnap.Items.Count - 1; i >= 0; i--)
{
string tt = listBoxSnap.Items[i].ToString();
int first = tt.IndexOf("Text: ");
int second = tt.IndexOf(",", first + 6);
string text = tt.Substring(first + 6, second - first - 6);
if (text != "" || text != null)
myList[i] = text;
}
我試過循環內循環和後線:
myList.Where(x => !string.IsNullOrEmpty(x)).ToArray();
但還是有與項目 「」
如果您不想將空字符串或null放入數組中,請使用&&,而不是||。更好的是,使用!string.IsNullOrEmpty(value)。 –
反轉它並使用'.Equals()'方法也會更好。 'if(!text.Equals(null)&&!text.Equals(string.empty))' – Draken
@Draken爲什麼Equals會更好?兩者最終都做了完全相同的事情。 – juharr