Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only first object in LINQ?

Tags:

c#

linq

c#-4.0

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?

like image 912
ApprenticeHacker Avatar asked Aug 05 '12 16:08

ApprenticeHacker


People also ask

How to get first item in LINQ c#?

C# Linq First() MethodUse the First() method to get the first element from an array. Firstly, set an array. int[] arr = {20, 40, 60, 80 , 100}; Now, use the Queryable First() method to return the first element.

What is first in LINQ?

First<TSource>(IEnumerable<TSource>) Returns the first element of a sequence. First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Returns the first element in a sequence that satisfies a specified condition.

How do I use FirstOrDefault?

Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List<double> val = new List<double> { }; Now, we cannot display the first element, since it is an empty collection. For that, use the FirstorDefault() method to display the default value.


1 Answers

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.

like image 158
Darin Dimitrov Avatar answered Sep 30 '22 13:09

Darin Dimitrov