Reputation: 22011
Basically I want to adapt this code for LINQ:
private Tile CheckCollision(Tile[] tiles)
{
foreach (var tile in tiles)
{
if (tile.Rectangle.IntersectsWith(Rectangle))
{
return tile;
}
}
return null;
}
The code checks each tile and returns the first tile that collides with the object. I only want the first tile, not an array of tiles like I would get if I use this:
private Tile CheckCollision(Tile[] tiles)
{
var rtn =
from tile in tiles
where tile.Rectangle.IntersectsWith(Rectangle)
select tile;
}
What should I do?
Upvotes: 5
Views: 3805
Reputation: 1038810
You could use the .First()
or .FirstOrDefault()
extension method that allows you to retrieve the first element matching a certain condition:
private Tile CheckCollision(Tile[] tiles)
{
return tiles.FirstOrDefault(t => t.Rectangle.IntersectsWith(Rectangle));
}
The .First()
extension method will throw an exception if no element is found in the array that matches the required condition. The .FirstOrDefault()
on the other hand will silently return null. So use the one that better suits your needs.
Notice that there's also the .Single()
extension method that you could use. The difference with .First()
is that .Single()
will throw an exception if more than one elements matches the condition whereas .First()
will return the first one.
Upvotes: 16