开发者

Using an expression lambda on a generic method on a generic collection

开发者 https://www.devze.com 2023-02-07 12:59 出处:网络
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).

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

  1. How does vm get its type? It is not defined elsewhere in the object instance.

  2. 开发者_StackOverflow中文版

    How does FirstOrDefault(vm => vm is AllCustomersViewModel) satisfy the source parameter requirement of FirstOrDefault? 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


  1. vm gets its type because Workspaces is a collection that contains a specific type. vm is automatically inferred to be that type.

  2. The source parameter of FirstOrDefault is Workspaces. It's an extension method on IEnumerable<T>, so the instance you call it on takes the place of the first parameter. That's what the this 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消