0

I want to remove items from a list of entities, when there is a concidence from a list (id). I have written this code, but I am guessing there is a better way to do it, and improve performance.

Here is my code:

List<int> toRemove; //includes the ids of the entities to be removed
        if (people.Count > 1)
            people.RemoveAll(x => people.Any(y => y != x && toRemove.Contains(x.ID)));
        else
            people.RemoveAll(x => toRemove.Contains(x.ID));
Juanito
  • 420
  • 1
  • 4
  • 18
DanielV
  • 2,076
  • 2
  • 40
  • 61
  • 4
    So you want all items [`except`](https://msdn.microsoft.com/en-us/library/vstudio/bb300779%28v=vs.100%29.aspx) the ones in your removal list? – DavidG Feb 12 '15 at 14:16
  • @DavidG I read about the method but it works only both lists have the same type of elements, I can force it to be List but then I won't have a List as a result – DanielV Feb 12 '15 at 15:05
  • 1
    @DanielV maybe [this](http://stackoverflow.com/a/853551/3806089) can be useful as well – Juanito Feb 13 '15 at 09:18
  • 1
    @Juanito excellent information, it doesn't apply to this question in a direct way, but really useful, thank you – DanielV Feb 13 '15 at 09:21

1 Answers1

2

Given a list of people, for example:

var people = new List<Person>
{
    new Person { ID = 1, Name = "Fred1" },
    new Person { ID = 2, Name = "Fred2" },
    new Person { ID = 3, Name = "Fred3" },
    new Person { ID = 4, Name = "Fred4" },
    new Person { ID = 5, Name = "Fred5" },
    new Person { ID = 6, Name = "Fred6" },
    new Person { ID = 7, Name = "Fred7" },
    new Person { ID = 8, Name = "Fred8" },
    new Person { ID = 9, Name = "Fred9" },
    new Person { ID = 10, Name = "Fred10" }
};

And a list of IDs to remove:

List<int> toRemove = new List<int> { 3, 4, 5 };

You can remove the unwanted entries like this:

people = people.Where(p => !toRemove.Contains(p.ID)).ToList();

Oh, and for completeness, here's a Person class to complete the example!

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
}

And to show it working:

https://ideone.com/ERP3rk

DavidG
  • 113,891
  • 12
  • 217
  • 223