1

I have two lists:

List<int> positionsThatCannotBeMovedTo =...
List<int> desiredLocations =...

I am trying to remove all of the positions which cannot be moved to from the desired locations to create a list of safe positions:

List<int> safePositions = new List<int>(uniquePositions);
safePositions.RemoveAll(positionsThatCannotBeMovedTo);

however it's throwing the error:

"Argument1: cannot convert from 'System.Collections.Generic.List' to 'System.Predicate'

I'm not entirely sure what this means or how I'm misusing the function. Is anybody able to explain this for me please? I am doing it this way because of the answer in this question:

Compare two lists for updates, deletions and additions

Community
  • 1
  • 1
Alec Gamble
  • 441
  • 3
  • 6
  • 16

3 Answers3

6

RemoveAll takes a Predicate<T>, but you are passing a list:

safePositions.RemoveAll(x => positionsThatCannotBeMovedTo.Contains(x));
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

There is another way to obtain a list with elements except the elements of another list

List<int> positionsThatCannotBeMovedTo = new List<int>() {1,2,3,4,5,6,7};
List<int> uniquePositions = new List<int>() {5,6,7,8,9,10};
List<int> safePosition = uniquePositions.Except(positionsThatCannotBeMovedTo).ToList();

MSDN on Enumerable<T>.Except

Steve
  • 213,761
  • 22
  • 232
  • 286
0

You could also accomplish this using the Except extension method. Assuming uniquePositions is your list of all your positions.

var safePositions = uniquePositions.Except(positionsThatCannotBeMovedTo).ToList();

Except is the set difference operator and as you are using lists of ints the default comparer is fine.

Bradford Dillon
  • 1,750
  • 13
  • 24