2010-10-10 40 views
4

我想知道如果一個方法來確定某個範圍的數組元素是否爲空。例如,如果數組被初始化爲具有值「」的10個元素,則如果數據稍後被分配給元素5,7,9;我可以測試元素0-3是否爲空,或者是否包含空字符串「」?C#:有沒有辦法確定一系列元素是否爲空?

+0

難道你不能簡單地用10個空值而不是10個空字符串來啓動數組嗎? (「」!= null) – 2010-10-10 22:45:31

+0

我的第一個破解就是像if(Array.IndexOf(array,「」)<4),它看到前四個元素是否有空白條目。似乎有點笨重,但。 – Sinaesthetic 2010-10-10 22:45:39

回答

5
array.Skip(startIndex).Take(count).All(x => string.IsNullOrEmpty(x)); 

所以,如果你想查詢元素0-3:

array.Skip(0).Take(4).All(x => string.IsNullOrEmpty(x)); 

爲清楚起見,我在那裏留下Skip

編輯:使其Take(4),而不是3按在對方的回答喬納森的評論(現在在我Guffa的評論;))。

編輯2:根據下面的註釋,在OP想看看這些單元的任意匹配:

array.Skip(0).Take(4).Any(x => string.IsNullOrEmpty(x)); 

因此改變AllAny

+0

只檢查元素0-2。 – Guffa 2010-10-10 22:53:48

+0

好吧,我認爲這是有道理的。但是,這不僅僅是檢查整個範圍是空白的嗎?我想我應該更具體。基本上我想要做的是確定該範圍內的任何元素是否包含空白 – Sinaesthetic 2010-10-10 23:03:11

+0

@Sinaesthetic,修改後的答案,但使用「Any」運算符而不是「All」。 – 2010-10-10 23:10:59

3
bool is0to3empty = myArrayOfString.Skip(0).Take(4).All(i => string.IsNullOrEmpty(i)); 
+3

不應該拿(4)? – 2010-10-10 22:50:50

+0

@Jonathan是的,但我不認爲確切的數字是真正的問題在這裏。 – 2010-10-11 04:26:55

+0

我擔心有人會看到Take(3),並且認爲它的意思是「將所有元素索引到3」。 – 2010-10-12 18:28:36

1

創建此擴展類,你可以從任何字符串數組稱之爲:

public static class IsEmptyInRangeExtension 
    { 
     public static bool IsEmptyInRange(this IEnumerable<string> strings, int startIndex, int endIndex) 
     { 
      return strings.Skip(startIndex).TakeWhile((x, index) => string.IsNullOrEmpty(x) && index <= endIndex).Count() > 0; 
     } 

    } 
2

的最直接,最有效的是簡單地通過數組的那部分循環:

bool empty = true;.. 
for (int i = 0; i <= 3; i++) { 
    if (!String.IsNullOrEmpty(theArray[i])) { 
    empty = false; 
    break; 
    } 
} 
if (empty) { 
    // items 0..3 are empty 
} 

另一種替代方法是使用擴展方法進行循環:

bool empty = theArray.Take(4).All(String.IsNullOrEmpty);