How do I check if a List contains an object of a certain type? C#

北城余情 提交于 2020-05-22 19:56:45

问题


I have a list (called Within), and it contains objects of type GameObject. GameObject is a parent class to many others, including Dog and Ball. I want to make a method that returns true if Within contains any object of type Ball, but I don't know how to do this.

I've tried using Count<>, Any<>, Find<> and a few other methods provided within C#, but I couldn't get them to work.

public bool DetectBall(List<GameObject> Within)
{
    //if Within contains any object of type ball:
    {
        return true;
    }
}

回答1:


if (within.OfType<Ball>().Any())

The generic parameter of all LINQ methods except Cast<T>() and OfType<T>() is used to allow the method call to compile and must be compatible with the type of the list (or for a covariant cast). They cannot be used to filter by type.




回答2:


in non-linq if you're interested

public bool DetectBall(List<GameObject> Within)
{
    foreach(GameObject go in Within)
    {
        if(go is Ball) return true;
    }

    return false;
}


来源:https://stackoverflow.com/questions/8216881/how-do-i-check-if-a-list-contains-an-object-of-a-certain-type-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!