Damiano Caprari Damiano Caprari - 1 year ago 66
C# Question

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..

In another Class, lets call it
Main
, i can use a function that retrieves me all instances of those classes as an array.

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.
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?

Answer Source

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;).

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download