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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With