0

This is probably a stupid question, but when I see code like this

var newList = list.OrderBy(x => x.Product.Name).toList();

I wonder that does the (x => x.Product.Name) mean?
Like, what is x and what does the => mean?

I don't know what to search for in order to obtain more information on this subject, any help would be appreciated, thank you.

2 Answers2

0

Look on google for Lambda Expression. Here is a link to the MS page for Lambda Expressions - https://msdn.microsoft.com/en-us/library/bb397687.aspx

czuroski
  • 4,316
  • 9
  • 50
  • 86
0

It's called a Lambda Expression.

A lambda expression is a way of passing a method as a parameter. The lambda expression above could be written as a method, possibly like this:

public string GetProductName(Thing x)
{
     return x.Product.Name;
}

So we see that x is a parameter into the method, or lambda expression in this case.

The OrderBy method in LINQ then uses this "method", or lambda expression, to know how to sort the list - OrderBy itself knows nothing about your objects or how to sort them, so we pass in a lambda which order by invokes.


In the case of IQueryable, lambda expressions are not actually code that gets invoked, but rather an expression tree is built. A lambda can be used to satisfy a delegate, or it can be used to build an expression tree. This is a bit of a complex subject, but worth mentioning.

vcsjones
  • 138,677
  • 31
  • 291
  • 286