如何从对象数组中过滤字符串

时间:2021-06-14 20:14:26

I have an array of objects like this:

我有一个像这样的对象数组:

 object[] test = {
        "Rock Parrot",
        "Crimson Rosella",
        "Regent Parrot",
        "Superb Parrot",
        "Red Lory",
        "African Emerald Cuckoo",
        1,2,3


};

How do i filter this array and get only an array of strings.

如何过滤此数组并仅获取字符串数组。

Thanks

谢谢

3 个解决方案

#1


6  

You can do this:

你可以这样做:

var stringsOnly = test.OfType<String>().ToArray()

#2


1  

string[] stringArray = test.Where(element => element is string).Cast<string>().ToArray();

#3


0  

You can do:

你可以做:

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());
}

If you run this code the response:

如果您运行此代码响应:

Rock Parrot
Crimson Rosella
Regent Parrot
Superb Parrot
Red Lory
African Emerald Cuckoo

You can convert to array :

你可以转换为数组:

var a = s.ToArray();

#1


6  

You can do this:

你可以这样做:

var stringsOnly = test.OfType<String>().ToArray()

#2


1  

string[] stringArray = test.Where(element => element is string).Cast<string>().ToArray();

#3


0  

You can do:

你可以做:

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());
}

If you run this code the response:

如果您运行此代码响应:

Rock Parrot
Crimson Rosella
Regent Parrot
Superb Parrot
Red Lory
African Emerald Cuckoo

You can convert to array :

你可以转换为数组:

var a = s.ToArray();