仅选择LINQ中的第一个对象? [英] Select only first object in LINQ?

查看:64
本文介绍了仅选择LINQ中的第一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想使此代码适合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;
}

代码检查每个图块,并返回与对象碰撞的第一个图块.我只想要 first 磁贴,而不想要像使用该磁贴那样的磁贴数组:

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;

}

我该怎么办?

推荐答案

您可以使用.First().FirstOrDefault()扩展方法,该方法允许您检索符合特定条件的第一个元素:

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

如果在数组中找不到与所需条件匹配的元素,则.First()扩展方法将引发异常.另一方面,.FirstOrDefault()会静默返回null.因此,请使用更适合您需求的产品.

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.

请注意,您还可以使用.Single()扩展方法.与.First()的区别在于,如果多个元素匹配条件,则.Single()将引发异常,而.First()将返回第一个.

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.

这篇关于仅选择LINQ中的第一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆