简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM