Using an expression lambda on a generic method on a generic collection
I am trying to understand the below use of a lambda expression. This code is taken from Josh Smith's excellent MVVM demo code (http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090055).
A method is called as follows:
AllCustomersViewModel workspace =
this.Workspaces.FirstOrDefault(vm => vm is AllCustomersViewModel)
as AllCustomersViewModel;
As used here, FirstOrDefault
has the following definition, as identified by Visual Studio 2010:
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
It is not clear to me
How does
vm
get its type? It is not defined elsewhere in the object instance.- 开发者_StackOverflow中文版
How does
FirstOrDefault(vm => vm is AllCustomersViewModel)
satisfy thesource
parameter requirement ofFirstOrDefault
? Is this somehow being implied?
I have been trying to use these resources to parse this out:
http://msdn.microsoft.com/en-us/library/bb397687.aspx
http://msdn.microsoft.com/en-us/library/bb397951.aspx
vm
gets its type becauseWorkspaces
is a collection that contains a specific type.vm
is automatically inferred to be that type.The
source
parameter ofFirstOrDefault
isWorkspaces.
It's an extension method onIEnumerable<T>
, so the instance you call it on takes the place of the first parameter. That's what thethis
in the method signature means.
Others have answered the question itself. Just as an aside though, this code would be clearer as:
AllCustomersViewModel workspace = this.Workspaces.OfType<AllCustomersViewModel>()
.FirstOrDefault();
Why bother creating your own operator when LINQ already includes one? (OfType)
The <TSource, bool>
predicate has the first parameter inferred as mentioned above, the second parameter (the boolean) is then supplying by the lambda expression vm => vm is AllCustomersViewModel
The meaning is give me the first (or the default value if none exists) Workspace where the item is an instance of AllCustomersViewModel.
精彩评论