Select only the first object in LINQ?

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 fragment and returns the first fragment that collides with the object. I need only the first tile, not an array of tiles, as I would get if I used this:

private Tile CheckCollision(Tile[] tiles)
{
    var rtn = 
        from tile in tiles
        where tile.Rectangle.IntersectsWith(Rectangle)
        select tile;

}

What should I do?

+5
source share
1 answer

You can use the extension method .First()or .FirstOrDefault(), which allows you to get the first element that matches a specific condition:

private Tile CheckCollision(Tile[] tiles)
{
    return tiles.FirstOrDefault(t => t.Rectangle.IntersectsWith(Rectangle));
}

.First() , , . , .FirstOrDefault() null. , .

, .Single(), . .First() , .Single() , , .First() .

+16

All Articles