简体   繁体   中英

Comparing two lists and deleting identical results c#

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

RemoveAll带有Predicate<T> ,但是您正在传递一个列表:

safePositions.RemoveAll(x => positionsThatCannotBeMovedTo.Contains(x));

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM