2

I got two List<Image> (ListA and ListB) and i need an efficient way to get the elements of ListA without the elements of ListB (A\B)

For example:

  • ListA contains Image1, Image2, Image3, Image4
  • ListB contains Image2, Image4
  • ListA \ ListB would be Image1, Image3

I'm relatively new to C# and open for some suggestions

flexwend
  • 47
  • 7

1 Answers1

4

If items of ListA are unique you can put a simple Linq query:

  using System.Linq;

  ...

  List<Image> result = ListA
    .Except(ListB)
    .ToList();

If you want to modify existing list (i.e. ListA):

  ListA.RemoveAll(image => ListB.Contains(image));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Thanks for the help! I realised that i have to implement the IEquatable Interface to my custom Image class – flexwend Sep 18 '19 at 08:09
  • @flexwend: well, yes, if you have to compare *different instances* which can be equal to one another (i.e. if `Image1` can be equal to `Image2`); in case images are equal if and only if they share the same *reference* you don't have to implement any `IEquatable` – Dmitry Bychenko Sep 18 '19 at 08:11