简体   繁体   English

与另一个数组中的元素相比,从数组中删除重复的元素

[英]Remove elements from Array that are duplicates if compared to elements in another Array

I have the SuperClass Tile extended in many SubClassess such as GroundTile , WallTile , TrapTile etc.. 我在许多子类中扩展了SuperClass Tile ,例如GroundTileWallTileTrapTile等。
In another Class, lets call it Main , i can use a function that retrieves me all instances of those classes as an array. 在另一个类中,我们称其为Main ,我可以使用一个函数来检索这些类的所有实例作为数组。

Main(){  
  void MyFunctionThatDoesThings(){
    GroundTile[] grounds = FindObjectsOfType<GroundTile>();
    WallTile[] walls = FindObjectsOfType<WallTile>();
    // ... *same code but for other Classes* ...
    Tile[] tiles = FindObjectsOfType<Tile>();
    // ... etc
  }
}

What I need to do is to filter from tiles array the elements that are not already present in the other arrays. 我需要做的是从tiles数组中过滤其他数组中不存在的元素。 Is there a way (or a Linq method) to do this other than Looping through the tiles array, checking if the current element is equal to any element in the other arrays, and if not keep it otherwise delete it? 除了遍历tiles数组,检查当前元素是否等于其他数组中的任何元素之外,还有其他方法(或Linq方法)来执行此操作,如果不保留,则删除它?

Tile[] tiles = FindObjectsOfType<Tile>().Except(
    Enumerable.Empty<Tile>()
        .Concat( grounds )
        ...
        .Concat( walls ) ).ToArray();

If you're already storing each array in it's own variable as you show above, then you can filter out the other arrays using the Except() extension method (which you get from using System.Linq; ). 如果您已经如上所示将每个数组存储在其自己的变量中,则可以使用Except()扩展方法( using System.Linq;获得Except()来过滤其他数组。

Then you can just do something like: 然后,您可以执行以下操作:

GroundTile[] grounds = FindObjectsOfType<GroundTile>();
WallTile[] walls = FindObjectsOfType<WallTile>();
TrapTile[] traps = FindObjectsOfType<TrapTile>();

Tile[] tiles = FindObjectsOfType<Tile>()
    .Except(traps)
    .Except(walls)
    .Except(grounds)
    .ToArray();

This might do as an example if I understood correctly: 如果我正确理解的话,这可以作为示例:

            List<int> l = new List<int> { 1, 2, 4 };
            List<int> s = new List<int> { 1, 2, 3 };
            var result = s.Where(x => l.Contains(x));

One way to do it is by using LINQ. 一种方法是使用LINQ。 Assuming you have an ID to identify a particular object. 假设您具有一个标识特定对象的ID。

GroundTile[] grounds = FindObjectsOfType<GroundTile>();
WallTile[] walls = FindObjectsOfType<WallTile>();
// ... *same code but for other Classes* ...
Tile[] tiles = FindObjectsOfType<Tile>();

var existingTiles = grounds.Union(walls);

tiles = tiles.Where(t => existingTiles.All(e => e.ID != t.ID)).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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