我有對象的一個這樣的數組的數組過濾字符串:如何從對象
object[] test = {
"Rock Parrot",
"Crimson Rosella",
"Regent Parrot",
"Superb Parrot",
"Red Lory",
"African Emerald Cuckoo",
1,2,3
};
如何過濾這個數組並獲得唯一的字符串數組。
感謝
我有對象的一個這樣的數組的數組過濾字符串:如何從對象
object[] test = {
"Rock Parrot",
"Crimson Rosella",
"Regent Parrot",
"Superb Parrot",
"Red Lory",
"African Emerald Cuckoo",
1,2,3
};
如何過濾這個數組並獲得唯一的字符串數組。
感謝
你可以這樣做:
var stringsOnly = test.OfType<String>().ToArray()
你可以這樣做:
object[] test = {
"Rock Parrot",
"Crimson Rosella",
"Regent Parrot",
"Superb Parrot",
"Red Lory",
"African Emerald Cuckoo",
1,2,3};
List<string> s = new List<string>();
foreach (var item in test)
{
if (typeof(string) == item.GetType())
s.Add(item.ToString());
}
如果你運行這段代碼的響應:
Rock Parrot
Crimson Rosella
Regent Parrot
Superb Parrot
Red Lory
African Emerald Cuckoo
您可以轉換數組:
var a = s.ToArray();
如果有任何'數組中null'值。這會崩潰。 – Blorgbeard
string[] stringArray = test.Where(element => element is string).Cast<string>().ToArray();
這可行,但你不需要'(string [])'。 – Blorgbeard
歡迎來到堆棧溢出:-) 請看[答]。您應該提供一些信息,說明爲什麼您的代碼可以解決問題。 僅有代碼的答案對社區沒有用處。 – JimHawkins
謝謝Blorgbeard - 修復 –
這對我不起作用。難道是因爲OfType缺少括號嗎? – Codeacula
哎呀,謝謝 - 修好了。 – Blorgbeard
多數民衆贊成在@Blorgbeard ......我也試過這個var stringOnly = Array.FindAll(測試,x => x是字符串);哪一個你認爲資源更好? – Harrobbed