I've been following this tutorial today to learn a bit about the Web API and noticed something - in the tutorial code, there was this line:
var product = products.FirstOrDefault((p) => p.Id == id);
As you can see the parameter "p" is provided in parentheses. Since it's not mandatory having it this way, I'm curious if there's any benefit to doing it that way or if it's just a preference of the developer?
In this case, it's purely developer preference.
Parenthesises are needed when you have more than one parameter. For example:
var singleString = someStrings.Aggregate((current, next) => current + Environment.NewLine + next);
The C# specification explicitly states that (p) => ... can be written as p => ...:
7.15 Anonymous function expressions
...
In an anonymous function with a single, implicitly typed parameter, the parentheses may be omitted from the parameter list. In other words, an anonymous function of the form
( param ) => expr
can be abbreviated to
param => expr
So there is no technical difference whatsoever, only personal preference.
Related
The ToDictionary() method call in this LINQ statement needs arguments. As it currently stands, the ToDictionary portion is a red squiggly, for lack of a better technical term. Error: No overload takes 0 arguments. Yeah, I know that.
I cannot add lambdas to the ToDictionary method call because Intellisense is overriding my lambda with its suggestion. In other words, if I type in "x ", it replaces it with XmlReader. Argh.
I've tried it with and without AsEnumerable. I borrowed most of this code from a StackOverflow post, but I added the dictionary portion.
Am I missing parentheses somewhere or something? Halllllp!
var props = (from p in _type.GetProperties()
let attr = p.GetCustomAttribute<ExcelExportAttribute>()
where attr != null && attr.ReportId.ToString() == reportID
select new {Prop = p, Att = attr })
.AsEnumerable()
.ToDictionary<PropertyInfo, ExcelExportAttribute>();
Error in VS
Severity Code Description Project File Line Suppression State Error CS1929 'IEnumerable<>' does not contain a definition for 'ToDictionary' and the best extension method overload 'Enumerable.ToDictionary(IEnumerable, Func, IEqualityComparer)' requires a receiver of type 'IEnumerable' WFG.UtilityLib.Excel C:\Users\kbessel\source\repos\WFG.UtilityLib.Excel\WFG.UtilityLib.Excel\ExcelExport.cs 142 Active
You need to completely leave out the generic types, like this:
.ToDictionary(x => x.Prop, x => x.Att);
The reason is that the extension method would need not two but THREE generic types: one for the "this" parameter, and two more for the "regular" parameters - or none, because the compiler can derive the types from the parameters.
You can specify all 3 types explicitly, but that would hardly serve any purpose because they can be derived automatically.
I cannot add lambdas to the ToDictionary method call because Intellisense is overriding my lambda with its suggestion. In other words, if I type in "x ", it replaces it with XmlReader.
This is a straightforward problem to overcome: type x, then press Esc to close down Intellisense drop-down. Continue typing the expression as needed:
var props = _type.GetProperties()
.SelectMany(p => new {Prop = p, Attr = p.GetCustomAttribute<ExcelExportAttribute>()})
.Where(p => p?.ReportId?.ToString() == reportId)
.ToDictionary(p => p.Prop, p => p.Attr);
It's amazing how little information there is on this. I found tons of tutorials explaining LINQ, but they don't explain this particular operator:
var Results = UserFavoritesContext.UserFavorites.Select(color => color.FavoriteColor);
"x => x.y"
Can someone please explain how this works? I get the general syntax and am able to use it to make queries, but it's like doing something without knowing what you're doing.
Suppose you have a list of people, and you want to iterate over them. You would write something like:
foreach(var person in people)
{
//do something to person
}
Note how you yourself chose the name person. It could've been any word, but you basically said "process every single item of the list as my person variable".
Now look at this LINQ query:
filteredPeopleList = people.Where(person => person.Name == "John");
Again, you basically chose person as a placeholder name for every object in the original list (one at a time). The above Linq query is equivalent to
foreach(var person in people)
{
if(person.Name == "John")
{
filteredPeopleList.Add(person);
}
}
To me, x => x.y is basically saying "for every variable we process (let's call it x), please perform the following operation on it (x.y, get the y property)"
I hope that explains it.
Edit
As a commenter who now deleted his comment mentioned, this isn't exclusively used in LINQ. A lambda expression doesn't have to iterate over an IEnumerable, it can be used to process a single item.
However, LINQ is by far the most common place to encounter lambdas, and I find their use very similar to the foreach loop, which is why I picked this example.
The => operator is used in lambda expressions.
The best way to think of this is a type of syntax for writing a function, where the left side of the operator is the parameters for the function and the right side is the body of the function e.g. this is a valid use of a lambda expression where its being used like a function:
Func<int, int> incrementFunction = i => i + 1;
int incrementedNumber = incrementFunction(1);
The name i in this case is an arbitrary variable name e.g. just like you would name a functions input parameter. Notice I didnt need to declare the input parameters type because the compiler will infer it. Also notice I dont need to include the "return" keyword or enclose the function body in a code block. It doesn't necessarily need any parameters either e.g.
Action myAction = () => Console.Write("something");
myAction();
When you use it in a linq expression, think of it as though the lambda function is being called on every element in the collection (which I believe is exactly what happens with linq to objects).
It's the syntax of a Lambda expression. If it helps you to remember... in a nutshell, the argument to pass (the parameter) is on the left of the => and the method(s) that use it are on the right hand side of it.
I hope this short summary explains it enough :)
That is a lambda expression, and it can be used as a selector from an object
You can conditionally select (or another operation orderby, count, etc) when the expression is true. For example:
Say you had a list of people and their details: ID, Name, City and Profession.
You could select a single person by using lambda to search for their specific ID:
public Person GetByID(int id)
{
Person selectedPerson = people.SingleOrDefault(person => person.ID == id);
return selectedPerson;
}
Same could be applied for a select on a city, this would be:
public List<Person> GetByCity(string city)
{
List<Person> selectedPeople = people.where(person => person.City == city);
return selectedPeople;
}
The lamda expression is where you place your operation variable, so in these cases the condition upon which you select the data. You can use it as a orderby variable much in the same way, in the next example I use two lamdas to perform two seperate functions
public List<Person> GetByCity(string city)
{
List<Person> selectedPeople = people.where(person => person.city == city)
.OrderByDescending(person => person.Name);
return selectedpeople;
}
I hope this helps at all
x => x.y is Lambda Expression introduced with C# 3.0. The general syntax is
parameter => executioncode
The Lambda Expression has 3 parts:
x on left hand side is the parameter.This can be a variable,delegate or an anonymous function.
=> read as "goes to", which acts as separator
x.y is an Expression to be evaluated.
For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared (source: MSDN).
Hope this would help you.
They're called Lamda expression:
https://msdn.microsoft.com/en-us/library/bb397687.aspx
var Results = UserFavoritesContext.UserFavorites.Select(color => color.FavoriteColor);
is similar to:
List<UserFavorite> Results = new List<UserFavorite>();
foreach(var item in UserFavorites)
{
Results.Add(item.FavoriteColor);
}
This is not specific to Linq.
It is the way you write a lambda expression.
The arrow => is the delimiter between your lambda parameters and its body.
I am newbie to EF how to use and - or in where clause in the entity framework
HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL attendanceDeviceShutdownTbl =
context.HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL
.FirstOrDefault(x => x.Device_ID.Equals(model.DeviceId) &&
x=>x.Device_Name=model.DeviceName);
the above code will not work but how can I make it works.
Expression lambda has following syntax param => expression. I.e. its like simple method, which have input parameter(s) and body. You define parameters only once and then use them in body of method or lambda:
HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL attendanceDeviceShutdownTbl =
context.HR_ATTENDANCE_DEVICE_SHUTDOWN_TBL.FirstOrDefault(x =>
x.Device_ID.Equals(model.DeviceId) && x.Device_Name == model.DeviceName);
In this case you have single parameter x which goes to anonymous function body. Body is an expression which should return boolean value and (usually) use parameter x. In your case lambda body should be
x.Device_ID.Equals(model.DeviceId) && x.Device_Name == model.DeviceName
Suggested reading: Lambda Expressions (C# Programming Guide). Also note == is a comparison operator. = is an assignment operator. Do not mix up with them.
Is it mandatory that lambda expression need to use when LINQ will be used, or are lambda expressions optional?
In lambda expressions, the sign => is always used. What does it mean?
customers.Where(c => c.City == "London");
Here c => is used but why?
What kind of meaning of using c =>. Please discuss in detail because I don't know lambda.
No, you don't have to use a lambda expression. For example, your Where example could be written as:
private static bool IsLondon(Customer customer)
{
return customer.City == "London";
}
...
var londoners = customers.Where(IsLondon);
That's assuming LINQ to Objects, of course. For LINQ to SQL etc, you'd need to build an expression tree.
As to why "=>" is always used in a lambda expression, that's simply because that's the way the operator is written - it's like asking why "+" is used for addition.
A lambda expression of "c => ..." is effectively giving the lambda expression a parameter called c... in this case generic type inference provides the type of c. The body provides either an action to perform or some calculation to return a value based on c.
A full-blown description of lambda expressions is beyond the scope of this answer. As a blatant plug for my book, however, they're covered in detail in chapter 9 of C# in Depth.
The lambda expression
c => c.City == "London"
is shorthand for something like
bool IsCustomerInLondon(Customer c)
{
return (c.City == "London");
}
It's just a very concise way of writing a simple function that returns a value. It's called an "anonymous function" because it's never assigned a name or a formal definition (the parameter types and the return type are inferred from the context).
(Actually, it's not just shorthand; lambda expressions are related to some other constructs called closures, which are very cool and powerful tools.)
Think about lambdas as anonymous of functions.
I'll try to explain it with following code.
public bool IsLondon(Customer customer)
{
return customer.City == "London";
}
Now we strip down function name and get rid of braces:
public bool Customer customer
return customer.City == "London";
We don't need return type, because compiler is able to deduce type from expression:
customer.City == "London";
In the same manner compiler knows about input type, so we don't need to specify it.
So basically, what we left with is
customer
return customer.City == "London";
And lambda syntax in c# is basically:
(parameter list) => "expression"
You can also write "multi-line" expressions, but then you have to surround your code with curly braces. Also you will need to use "return" statement, like you usually do.
Jon already answered,
but I'd like to add this.
In the example you have given, imagine Linq looping over all customers,
and c is simply a reference to each item in the enumerable:
var result = new List<Customer>();
foreach(var c in customers)
{
if (c.City == "London")
result.Add(c);
}
return result;
It's a variable like any other, it does not have to be a single named one,
but it's just a convention of some sort.
you do not need to use lambda expressions on Lİnq to sql or Entities; here is an alternative way of your code;
you code :
customers.Where(c => c.City == "London");
the other way;
var query = from cs in customers
where cs.City == "London"
select cs;
this is the another way. it is up to you.
Lambda and linq are quite separate. You can use one without using the other (there are parts of linq that depend on lambda expressions, but we want to keep it simple :-) )
A lambda expression is an anonymous
function that can contain expressions
and statements, and can be used to
create delegates or expression tree
types.
This was from MSDN. (http://msdn.microsoft.com/en-us/library/bb397687.aspx )
To make it short (it's much more complex) you can use a lambda expression to make a local function. what you put before the => (in your example the c) will be the parameter of the function. The return type is "discovered" by the C# compiler.
c => c.City == "London" is nearly equivalent to:
delegate (TheObjectTypeOfC c) {
return c.City == London
};
(the difference is that some lambda expression are delegates and also expressions, but please ignore this, you won't need it for some time)
If/when the compiler isn't able to infer the types of the parameters, you can force them: (MyObject p) => p.SomeProperty != null. Here you are telling the compiler that p is a parameter.
While here I showed you what are called "expression lambdas", you can even do "statement lambdas":
p => {
for (int i = 0; i < 10; i++) {
if (p.SomeProperty == 0) {
return true;
}
}
return false;
}
(I won't tell you what are the "behind the scenes" differences between expression lambdas and statement lambdas. If you want to know them, read the msdn page I pointed before)
No it is not necessary at all.
We have two ways to write LINQ queries.
One is query method and other is builder method. You only need to put lambda expression in case of builder method.
For example, if we want to find all those students from some Students object that have more marks than 70.
but we can do this thing in LINQ with following syntax
var data = from p in stdList
where p.marks > 70
select p;
or
var data = stdList.Where(p=>p.marks > 70);
later approach is builder method, in Where function, we are passing lambda expressions.
Lambda expressions are just short cuts of doing things you can always use LINQ queries but if you want to avoid whole query syntax for just applying a simple condition you can just use LINQ builder methods (which asks for lambda expressions) in lambda expressions, you always define some alias and then perform your operation.
As far as => operator is concerned, It works just like assignment operator.
For example:
(p) => p.Gender == “F”
It means “All persons p, such that person’s Gender is F”
In some literature this is called “predicate”. Another literature terminology is “Projection”
(p) => p.Gender ? “F” : “Female”
“Each person p becomes string “Female” if Gender is “F””
This is projection, it uses ternary operator.
Although i explained with very basic examples but i hope this would help you . . . :)
I'm constructing an expression tree (Expression<Func<PlainAddress, bool>> predicate) to pass it to the IQueryable.Where function for HNibernate to execute the query. When I pass:
predicate = y => y.Address.City == geoObject.Name;
everything works fine. When I pass:
var x = Expression.Parameter(typeof(PlainAddress));
Expression<Func<PlainAddress, string>> expression = y => y.Address.City;
predicate = Expression.Lambda<Func<PlainAddress, bool>>(
Expression.Equal(
Expression.Invoke(expression, x),
Expression.Constant(geoObject.Name)),
x);
I get the following exception
Invalid path: 'y.Address.City'
[.Where(NHibernate.Linq.NhQueryable`1[BPPDicsManager.Domain.Entities.PlainAddress],
Quote((60ee8287-3f42-426a-8c15-41f62f58623c, ) => (String.op_Equality((y, ) =>
(y.Address.City)60ee8287-3f42-426a-8c15-41f62f58623c, p1))), )]
What am I doing wrong? What are the difference between these 2 options?
I'm not familiar with NHibernate, but I can try to explain the differences between the two expressions.
1.The major difference is the use of Expression.Invoke in sample # 2, which creates an InvocatonExpression that "represents an expression that applies a delegate or lambda expression to a list of argument expressions". This introduces a kind of indirection - loosely speaking,
Sample # 1 is:
y => y.Address.City == geoObject.Name;
whereas Sample # 2 is something like:
x => new Func<PlainAddress, string>(y => y.Address.City).Invoke(x)
== geoObject.Name
You can get the second sample closer to the first by using Expression.Property to create the appropriate MemberExpressions :
var predicate = Expression.Lambda<Func<PlainAddress, bool>>(
Expression.Equal(
Expression.Property(Expression.Property(x, "Address"), "City"),
Expression.Constant(geoObject.Name)),
x);
This is now closer to:
x => x.Address.City == AsStringLiteral(geoObject.Name)
(I'm guessing this will be sufficient to get the predicate to work with NHibernate.)
2.The other difference of course, is the use of Expression.Constantin sample # 2, which will eagerly evaluate the value of geoObject.Name and turn that into a literal in the expression-tree. You're going to need a lot more work if you want to 'emulate' the hoisting of the geoObject variable (or perhaps this?) as in sample # 1.