Reputation: 6217
Simple question here, but this has been killing me trying to get this to work...
I have a class, called Taxonomy
. There is a property called, WebName
, I get a list of Taxonomy
classes, and would like to use .RemoveAll
to remove any of the Taxonomy's within the list with the WebName.ToLower()
equal to either "n/a"
or "other"
. WebName
property is of type string.
This is what I tried so far:
List<Taxonomy> theNeighborhoods = new List<Taxonomy>();
Taxonomy aNeighborhood = GetCachedNeighborhoodTaxonomy(); // Returns the Parent Taxonomy
theNeighborhoods = aNeighborhood.Children.ToList(); // This gives me a list of Taxonomy classes
How can I change theNeighborhoods
List to only select values that do not have "n/a" or "other" in the WebName
property of each Taxonomy
?
theNeighborhoods = aNeighborhood.Children.ToList().RemoveAll(a => a.WebName.ToLower() == "n/a" || a.WebName.ToLower() == "other").ToList();
The above code gives me error, something like int
has no extension ToList
How to do this with .RemoveAll
?
Upvotes: 0
Views: 153
Reputation: 6866
You could do one of two things. First you could use a where from LINQ:
theNeighborhoods = aNeighborhood.Children.Where(a => a.WebName.ToLower() != "n/a" && a.WebName.ToLower() != "other").ToList();
Alternatively you could call RemoveAll after getting the list, like so:
theNeighborhoods = aNeighborhood.Children.ToList();
theNeighborhoods.RemoveAll(a => a.WebName.ToLower() == "n/a" || a.WebName.ToLower() == "other").ToList();
RemoveAll returns an int that represents how many items were removed. That is why you got the error you did. I suggest looking up the documentation on RemoveAll.
Upvotes: 2
Reputation: 73442
Try this:
theNeighborhoods = aNeighborhood
.Children
.Where(a => a.WebName.ToLower() != "n/a" &&
a.WebName.ToLower() != "other")
.ToList();
Your code doesn't work because RemoveAll
returns an int
not the List<T>
or IEnumerable<T>
.
Also worth noting that you're calling ToList
twice, ToList
isn't free. It involves creation of new array and copying the items. So avoid redundant use of ToList
.
Upvotes: 4
Reputation: 246
Try only:
aNeighborhood.Children.ToList().RemoveAll(a => a.WebName.ToLower() == "n/a" || a.WebName.ToLower() == "other");
You cannot write ToList() because RemoveAll return the number of elements removed (int).
Upvotes: 0