Unity - 如何检查列表中的项目是否具有相同的值?

Unity - How to check if items within a list are the same value?

我有一个 Vector3Int 类型的列表,其中包含我的代理移动的结束位置,我想比较这些值以查看它们是否相等,

伪代码;

if (2 or more items within the list are the same value) {
  create a new end of path location for one or more of the agents  
}

在此先感谢您的帮助

有几种方法可以做到。

您可以 运行 使用 LINQ 查询的循环。它会检查列表中的每个项目,看看列表中是否有超过 1 个项目。 LINQ 的 Count() 版本允许您比较值。

bool HasDuplicates = false;
foreach (var item in MyList) {
    if (MyList.Count(i => i.x == item.x && i.y == item.y) > 1) {
        HasDuplicates = true;
        break;
    }
}

或者您可以使用 Distinct() 创建第二个列表,每个值只有 1 个。然后比较两个列表的计数。如果不同的计数较低,则列表中一定有重复项。

var HasDuplicates = (MyList.Distinct().Count < MyList.Count)