tags:

views:

110

answers:

1

I need to cast: IQueryable<PARENT> to IQueryable<Child>.

IQueryable<PARENT> query = GetParents();

IQueryable<CHILD> result = query.Select(t => t.Children);

This doesn't work, unable to convert EntitySet to IQueryable. Thanks

A: 

Use:

IQueryable<CHILD> result = query.SelectMany(t => t.Children);

The query returns all cild items of the parent, childs referenced by multiple parents will be returned multiple times.

To get the distinct rows use - you will have to implement a class that Implements IComparer though, to do a custom filtering. Distinct() will look at the instances and not the values.

IQueryable<CHILD> result = query.SelectMany(t => t.Children)
                                .Distict(new Comparer<CHILD>());

Distinct() removes duplicats from the query.

Aternatively you can use grouping to create a grouping for the children:

IEnumerable<CHILD> result = query.SelectMany(t => t.Children)
                                 .GroupBy(x => new CHILD { 
                                      id = x.id 
                                      // add other properties here
                                 })
                                 .Select(g => g.Key);

Instead of new CHILD { } you could also use new { } to create an anonymous result, in this case you should replace IEnumerable<CHILD> with var.

To perform a type cast in Linq you can use - although I would assume that this will not work in you case:

someQuery.OfType<TypeToCastTo>().Cast<TypeToCastTo>();

OfType<T>() filters the items so that Cast<T>() can perform the type cast.

Obalix
Thank you for reply.
Victor