bulltorious
bulltorious

Reputation: 7887

List(T) RemoveAll() not working as intended...?

Let's say I have a list of User objects with two properties...ID and Name

List<User> lst = List<User>();

I fill it up with a bunch of Users. Ok, now I want to trim my list using RemoveAll() and this function.

private Boolean IsExisting(int id) {
//blah blah
return true;
//blah blah
return false;
}

So I use this statement:

gdvFoo.DataSource = lst.RemoveAll(t => IsExisting(t.ID));

It is my understanding that whenever IsExisting returns true that element should be removed from lst, but what happens, strangely enough, is it returns an integer?, not a truncated list and I received the following error message:

Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource.>

Upvotes: 4

Views: 11234

Answers (6)

gprasant
gprasant

Reputation: 16023

Instead of RemoveAll(), you could try using IEnumerable's filter where you would say something like :

var filteredList = lst.Where(item => IsExisting(item.Id)) 

This makes the code a little more easier to read and focusses on the objective of the task at hand, rather than how to look at implementing it.

Upvotes: 3

Brosto
Brosto

Reputation: 4565

The RemoveAll is modifying the list and returning the number of items removed. You just set your datasource to the list in a second step.

lst.RemoveAll(t => IsExisting(t.ID));
gdvFoo.DataSource = lst;

Upvotes: 1

SpeksETC
SpeksETC

Reputation: 1013

RemoveAll() returns the number of elements removed. You need to do this:

lst.RemoveAll(t => IsExisting(t.ID)); 
gdvFoo.DataSource = lst;

Upvotes: 6

Rowland Shaw
Rowland Shaw

Reputation: 38130

List<T>.RemoveAll(...) has a return type of int which is not an IListSource, IEnumerable nor IDataSource

Upvotes: 1

Bryan Watts
Bryan Watts

Reputation: 45445

List.RemoveAll method

The method removes all matching instances from the list on which you called it. This modifies the existing list, rather than returning a new one.

The return value is the number of rows removed.

Upvotes: 7

spender
spender

Reputation: 120400

The docs are very clear about what's going on:

Return Value Type: System.Int32 The number of elements removed from the List .

Perhaps the following Linq would be more in line with your expectations?

lst.Except(t => IsExisting(t.ID)).ToList();

Upvotes: 3

Related Questions