我有一個包含一個變量:
有時候字符串數組,有時串
例如數組的數組:
訪問數組項?
var words = a LINQ to XML query;
//words == { "01", "02", "03", ... }
//or
//words == { {"01", "02", "03"}, {"04", "05", "06"}, ... }
現在,我想用for statement
訪問每個項目的words
陣列 你能指導我嗎?
感謝
我有一個包含一個變量:
有時候字符串數組,有時串
例如數組的數組:
訪問數組項?
var words = a LINQ to XML query;
//words == { "01", "02", "03", ... }
//or
//words == { {"01", "02", "03"}, {"04", "05", "06"}, ... }
現在,我想用for statement
訪問每個項目的words
陣列 你能指導我嗎?
感謝
(注:請參見編輯...)
如果不事先居然是否知道你已經有了一個字符串數組或字符串數組的數組,你需要有條件呼叫SelectMany
:
string[][] multi = words as string[][];
string[] flattened = multi == null ? words : multi.SelectMany(x => x).ToArray();
請注意,在這種情況下,如果您更改flattened
的內容,這將更改words
(如果這已經是平坦的)或只是更改副本(如果它是鋸齒狀的陣列)。如果你想保持一致,你可以調用words.ToArray()
在有條件的經營者的第二個操作數:
string[] flattened =
multi == null ? words.ToArray() : multi.SelectMany(x => x).ToArray();
有沒有辦法可以避開不確定性入手關係嗎?特別是,如果您控制涉及的LINQ to XML查詢,您應該能夠使它們提供一致的結果類型。
編輯:我剛剛意識到,如果你不知道數據的類型開始,那麼words
大概宣佈爲object
或IEnumerable
。在這種情況下,你會想是這樣的:
public string[] Flatten(object words)
{
string[][] multi = words as string[][];
if (multi != null)
{
return multi.SelectMany(x => x).ToArray();
}
string[] single = words as string[];
if (single != null)
{
return single.ToArray(); // Defensive copy; remove if not needed
}
throw new ArgumentException("Argument must be string[] or string[][]");
}
這仍然是真正的噁心 - 你一定要儘量讓查詢給你一些一致的結果類型,而不是。
@Jon - 我不確定歧義是否是一個問題。我在'string []'和'string [] []'上嘗試了'SelectMany',它在兩種情況下都能正常工作。 – 2010-03-10 07:35:46
SelectMany在一個字符串[]上會給你一個'IEnumerable
你說得對。我在測試中只使用了單個字符串,所以看起來很棒。這是一個壞主意。 – 2010-03-10 09:01:01
您可以將第二種形式轉換爲首先使用的SelectMany:
string[] words = words2.SelectMany(x => x).ToArray();
...最後調用'ToArray()',當然,如果你想要編譯的話。或者只是使用'IEnumerable
謝謝Jon,完成! – 2010-03-10 07:24:39
'words'變量的類型是什麼? – 2010-03-10 07:22:37
正如我在帖子中提到的那樣,它是一個數組。 – 2010-03-10 17:03:48