Polymorphic LINQ Query
Having a bit of a problem getting my LINQ query to return the object type I want to work with. I'm pretty close just need a little bit of input.
I have five tables, Objects, People, Locations, Collections, and CollectionEntries.
Object is the base class for People, Locations, and Collections. A Collection has many CollectionEntries which may contain entries to People, Locations, and Collections.
Given a specific collection I want to write the LINQ query to retreive the People in that collection.
So far I have this, which returns me a list of CollectionEntries ( they correspond to the People entries, yay half way! ) but I would rather have it return the instances of the People.
var people = collection.CollectionEntries.Where(
entry => entry.Ob开发者_如何转开发ject is Person ).ToList();
I have tried doing this:
var people = collection.CollectionEntries.Where(
entry => entry.Object is Person ).OfType<Person>().ToList();
but it doesn't return anything. Any suggestions of how to get a list of People from my Collection?
Try:
var people = collection.CollectionEntries.Where( entry => entry.Object is Person )
.Select(entry => (Person)entry.Object)
.ToList();
or
var people = collection.CollectionEntries.Where( entry => entry.Object is Person )
.Select(entry => entry.Object)
.Cast<Person>()
.ToList();
They should both work with your example.
Try this:-
var people = collection.CollectionEntries.Select( entry => entry.Object).OfType<Person>().ToList();
You needed to project the list to get to the .Object
first and then filter according to the type.
Here is an alternative way of writing this is to use the let
keyword inside query syntax
(then you can perform just one cast using the as
keyword, which may be more efficient):
var people =
(from e in collection.CollectionEntries
let pers = entry.Object as Person
where pers != null select pers).ToList();
精彩评论