简体   繁体   中英

Remove duplicated elements List<Vector3> Mono / C# - Unity3D

I need to remove the duplicates of elements in my Vector3 list. For Example, here is a list:

List<Vector3> PointsToGo = new List<Vector3>();

PointsToGo.Add(new Vector3(1, 1, 1));
PointsToGo.Add(new Vector3(2, 2, 2));
PointsToGo.Add(new Vector3(1, 1, 1)); // Get this one or the first one out
PointsToGo.Add(new Vector3(4, 4, 4));

Do you know how to solve this problem ? Maybe Linq can help me ?

Thanks for your answer!

Here is your solution

PointsToGo = PointsToGo.Distinct().ToList();

Note that you have add using System.Linq; to the top your code.

If you don't want to use Linq (which is a good thing according to Unity doc) you an use the following:

List<Vector3> list = new List<Vector3>(new HashSet<Vector3>(originalListWithDuplicate));

The other solution is to use HashSet collection instead. This is the purpose of that collection, avoiding duplicates. You may have to implement IEqualityComparer so it behaves exactly as you need it.

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