我有一个像这样的对象数组:
object[] test = {
"Rock Parrot",
"Crimson Rosella",
"Regent Parrot",
"Superb Parrot",
"Red Lory",
"African Emerald Cuckoo",
1,2,3
};
如何过滤此数组并仅获取字符串数组。
由于
答案 0 :(得分:6)
你可以这样做:
var stringsOnly = test.OfType<String>().ToArray()
答案 1 :(得分:1)
string[] stringArray = test.Where(element => element is string).Cast<string>().ToArray();
答案 2 :(得分:0)
你可以这样做:
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();