By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,459 Members | 1,472 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,459 IT Pros & Developers. It's quick & easy.

Use Linq to remove objects from list?

P: n/a
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<MyObjobjList = (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
Jun 27 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
LINQ for query; not manipulation.

However, List<Tprovides a predicate-based RemoveAll that does what you
want:

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

If it isn't List<Tbut 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
Jun 27 '08 #2

P: n/a
HI Mark,

"Marc Gravell" <ma**********@gmail.comschrieb im Newsbeitrag
news:uF**************@TK2MSFTNGP03.phx.gbl...
LINQ for query; not manipulation.
you are right, but LINQ is so mighty, that I was hoping for that too ;-)

However, List<Tprovides a predicate-based RemoveAll that does what you
want:

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

Regards
Rainer
Jun 27 '08 #3

P: n/a
Rainer Queck wrote:
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<MyObjobjList = (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
Jun 28 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.