Which query expression should you use?

You are developing a new feature in the application to display a list of all bundled products.
You need to write a LINQ query that will return a list of all bundled products. Which query expression should you use?

You are developing a new feature in the application to display a list of all bundled products.
You need to write a LINQ query that will return a list of all bundled products. Which query expression should you use?

A.
context.Parts.Cast<Product>()
.Where(p => p.Descendants.Any(d => d is Product))

B.
context.Parts.OfType<Product>()
.Where(p => p.Descendants.Any(d => d is Product))

C.
context.Parts.Cast<Product>()
.ToList()
.Where(p => p.Descendants.Any(d => d is Product))

D.
context.Parts.OfType<Product>()
.ToList()
.Where(p => p.Descendants.Any(d => d is Product))

Explanation:
OfType() Filters the elements of an IEnumerable based on a specified type.

Enumerable.OfType<TResult> Method
(http://msdn.microsoft.com/en-us/library/bb360913.aspx)



Leave a Reply 6

Your email address will not be published. Required fields are marked *


qwer

qwer

1) Very unclear question. may be class diagram is lost? 2) why not B?

Ed van Gageldonk

Ed van Gageldonk

I agree, unclear and a diagram would have been helpful to say the least.
The only reason I can think of to prefer D in favor of B is “…that will return a list…”, a list instead of some generic collection.

Gaius

Gaius

This is just a guess, but I think ToList() is required in order to use the “is” operator, since I don’t think LINQ maps that operator to SQL like it does with OfType().

Artem

Artem

I agree wuth Gaius, linq to sql queryprovider probably won’t parse “is” statement

Lyubomir Petrovski

Lyubomir Petrovski

It’s D because B returns IQuerable. The Enumerable.OfType() method is implemented by using deferred execution.

Jim BBQ

Jim BBQ

Thanks for the answer! 🙂