Curtis
Curtis

Reputation: 13

Best way to obtain objects from a collection that can be cast to a specific type using Linq

I'm trying to obtain all the Point objects in the a more general collection of Entities using Linq. Please refer to the comments in the code below. It appears that .Cast() and .OfType() do not seem to do what I need. Is the code below the best option?

// IHost has an Entities collection that contains different types of entities that implement IEntity, and one of specific types may be a Point object.
    public System.Linq.ParallelQuery<Point> GetPoints(IHost entityHost)
    {
        // Is this the best way to get a collection of Points from the Entities, using Linq?
        // I believe Entities.OfType<Point> does not work because the type of item in Entities is IEntity
        // I believe Entities.Cast<Point> does not work because there will be exceptions due to non-Point objects in the collection
        return entityHost.Entities.Where(o => o is Point).Cast<Point>();
    }

Upvotes: 0

Views: 66

Answers (1)

D Stanley
D Stanley

Reputation: 152521

OfType combines those two operations:

 return entityHost.Entities.OfType<Point>()

I believe Entities.OfType<Point> does not work because the type of item in Entities is IEntity

No, that's the declared type of Entities. OfType looks at the actual type of each item, and adds it to the result if it "is" a Point. By "is" I mean "can be cast to" - literally using the is operator:

static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source)      
{
    foreach (object obj in source) {
        if (obj is TResult) yield return (TResult)obj;
    }
}

Upvotes: 5

Related Questions