Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

c# - Difference between OfType<>() and checking type in Where() extension

Other than readability, what is the difference between the following linq queries and when and why would I use one over the other:

IEnumerable<T> items = listOfItems.Where(d => d is T).Cast<T>();

and

IEnumerable<T> items = listOfItems.OfType<T>();

Update: Dang, sorry introduced some bugs when trying to simplify my problem

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let us compare three methods (pay attention to generic arguments):

  1. listOfItems.Where(t => t is T) called on IEnumerable<X> will still return IEnumerable<X> just filtered to contain only elements of the type T.

  2. listOfItems.OfType<T>() called on IEnumerable<X> will return IEnumerable<T> containing elements that can be casted to type T.

  3. listOfItems.Cast<T>() called on IEnumerable<X> will return IEnumerable<T> containing elements casted to type T or throw an exception if any of the elements cannot be converted.

And listOfItems.Where(d => d is T).Cast<T>() is basically doing the same thing twice - Where filters all elements that are T but still leaving the type IEnumerable<X> and then Cast again tries to cast them to T but this time returning IEumerable<T>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...