0

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

0

3 Answers 3

6

You can do this:

var stringsOnly = test.OfType<String>().ToArray()
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't work for me. Could it be because OfType is missing parenthesis?
thats great @Blorgbeard ... i also tried this var stringOnly= Array.FindAll(test, x => x is string); which one do you think is better on resources.
I imagine that practically speaking both are "fast enough". If you are concerned, I suggest you race your horses :P
1
string[] stringArray = test.Where(element => element is string).Cast<string>().ToArray();

2 Comments

Welcome to stack overflow :-) Please look at How to Answer. You should provide some information why your code solves the problem. Code-only answers aren't useful for the community.
Thanks Blorgbeard - fixed
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 Comment

This will crash if there are any null values in the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.