linqcastingplinq

C#: Chained Linq methods and casting


I have a little game, where I implemented some collision detection. Now I want to get a list of all items of a specific type, which are colliding with the current "Entity" object. I want to do something like this:

    public List<T> GetCollidingObjects<T>() where T : Entity
    {
        return this.Game.World.Entities
            .AsParallel()
            .Where(e => e.IsColliding(this))
            .Where(e => e is T)
            .ToList<T>();
    }

I get the following error:

Instance argument: cannot convert from "System.Linq.ParallelQuery<GameName.GameObjects.Entity>" to "System.Collections.Generic.IEnumerable<T>"

Can anyone explain, why this happens?

Thank you!


Solution

  • You cannot use ToList() like that. The generic parameter you supply (if you choose to do so) must match the type of the sequence. It's a sequence of Entity, not T.

    Anyway, you should use OfType() to do the filtering, that's what it's there for.

    public List<T> GetCollidingObjects<T>() where T : Entity
    {
        return this.Game.World.Entities
            .OfType<T>()
            .AsParallel()
            .Where(e => e.IsColliding(this))
            .ToList();
    }