How to remove every occurrence from an array

Viewed 115

I'm trying to do it this way, but I get this error "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string[]'. An explicit conversion exists (are you missing a cast?)"

How can I cast this correctly, or is there a better way to do this?

string[] text = {"abc", "def", "ghi", "?", "jkl", "?"};
text = text.Where(x => x.Equals("?"));

2 Answers

Because Where() method doesn't return an array, it returns IEnumerable<>. You need to add ToArray() after Where().

string[] text = {"abc", "def", "ghi", "?", "jkl", "?"};
text = text.Where(x => x.Equals("?")).ToArray();

Instead of an array, use a List<T> which is a wrapper over an array. Then you could simply do

var text = new List<string>{ "abc", "def", "ghi", "?", "jkl", "?" };
text.RemoveAll(s => s == "?");
Related