Use Linq to remove objects from list?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rainer Queck

    #1

    Use Linq to remove objects from list?

    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<MyObjobjLi st = (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


  • Marc Gravell

    #2
    Re: Use Linq to remove objects from list?

    LINQ for query; not manipulation.

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

    MyList.RemoveAl l(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

    Comment

    • Rainer Queck

      #3
      Re: Use Linq to remove objects from list?

      HI Mark,

      "Marc Gravell" <marc.gravell@g mail.comschrieb im Newsbeitrag
      news:uFcThr41IH A.4572@TK2MSFTN GP03.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.RemoveAl l(obj =obj.Id 25);
      Thanks, that will definately do too.

      Regards
      Rainer


      Comment

      • =?ISO-8859-1?Q?Arne_Vajh=F8j?=

        #4
        Re: Use Linq to remove objects from list?

        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<MyObjobjLi st = (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

        Comment

        Working...