Use Linq to remove objects from list?

R

Rainer Queck

Hello NG,

is it possible to use linq to remove certain objects from a generic list?

Something more or less like:

from obj in MyList
where obj.Id > 25
delete obj

I know that I can do the following
List<MyObj> objList = (from o in MyList where o.Id>25 select o).ToList();
and then remove all returnt objects explicitly from "MyList" using
MyList.Remove(...)

Thanks for hints and infos...

Regards
Rainer Queck
 
M

Marc Gravell

LINQ for query; not manipulation.

However, List<T> provides a predicate-based RemoveAll that does what you
want:

MyList.RemoveAll(obj => obj.Id > 25);

If it isn't List<T> but something else instead (assume we just know
IList<T>) then you'll need to build a standalone set of the things to
remove, then remove them one by one...

Marc
 
R

Rainer Queck

HI Mark,

Marc Gravell said:
LINQ for query; not manipulation.
you are right, but LINQ is so mighty, that I was hoping for that too ;-)

However, List<T> provides a predicate-based RemoveAll that does what you
want:

MyList.RemoveAll(obj => obj.Id > 25);
Thanks, that will definately do too.

Regards
Rainer
 
A

Arne Vajhøj

Rainer said:
is it possible to use linq to remove certain objects from a generic list?

Something more or less like:

from obj in MyList
where obj.Id > 25
delete obj

I know that I can do the following
List<MyObj> objList = (from o in MyList where o.Id>25 select o).ToList();
and then remove all returnt objects explicitly from "MyList" using
MyList.Remove(...)

You can do the workaround as:

MyList = (from o in MyList where o.Id <= 25 select o).ToList();

technically it is not removing from the list but having the
reference point to a new list.

But it the net result is the same.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top