Find And Remove Items From Collection

后端 未结 4 1162
北荒
北荒 2021-01-07 22:15

What is the best way to remove a set from a collection, but still keep the items that were removed in a separate collection?

I have written an extension method that

4条回答
  •  半阙折子戏
    2021-01-07 23:15

    I don't agree that it is the most efficient - you are calling the predicate match twice on each element of the list.

    I'd do it like this:

        var ret = new List(); 
        var remaining = new List(); 
        foreach (T t in lst) {
            if (match(t)) 
            { 
                ret.Add(t); 
            } 
            else 
            { 
                remaining.Add(t); 
            } 
        }
        lst.Clear();
        lst.AddRange(remaining);
        return ret; 
    

提交回复
热议问题