tags:

views:

76

answers:

3

Hello:

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.Object 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?

+3  A: 

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.

Ben Robinson
Ended up using the select method but had to use entry.Object rather than just entry. Thanks for the prompt response!
Matthew
Oops yes silly me, i have corrected the answer now. BTW you can use backticks ` to wrap code snippets in comments
Ben Robinson
+2  A: 

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.

Hightechrider
+1  A: 

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(); 
Tomas Petricek
Very slick! I like it!
Matthew