I am looking for a very simple - basic - no hardcore programming mumbo jumbo, simply put a generalized overview of a Lambda Expression in layman's terms.
A lambda expression is, simply put, a re-useable expression which takes a number of arguments:
x => x + 1;
The above expression reads "for a given x, return x + 1".
In .NET, this is powerful, because it can be compiled into an anonymous delegate, a nameless function you can declare inline with your code and evaluate to get a value:
int number = 100;
Func<int, int> increment = x => x + 1;
number = increment(number); // Calls the delegate expression above.
However, the real power of a lambda expression is that it can be used to initialize an in-memory representation of the expression itself.
Expression<Func<int, int>> incrementExpression = x => x + 1;
This means that you can give that expression to something like LINQ to SQL and it can understand what the expression means, translating it into a SQL statement that has the same meaning. This is where lambdas are very different from normal methods and delegates, and normally where the confusion begins.
Lambda Expressions are inline functions that have a different syntax to regular functions.
Example Lambda Expression for squaring a number.
x => x * x
A small unnamed inline method. Is that basic enough for you? I'm not sure what you are looking for exactly.
You also said in "layman's" terms - I presume that you have some level of software development experience (so not a complete layman)
In non functional programming languages expressions (that act on variables) perform calculations and they perform those calculations once.
Lambda expressions allow you to define (in an expression) via different syntax code that can work on a list and can conceptually be considered a function.
You could simplify this to say "They let you define functions in expressions".
Does not quite get to the "why". The why is the more interesting, in my opinion. Lambda expression allow for the manipulation of functions and partial functions.
Related
I have the basic understanding of select method in linq.
var arrayIndex = Enumerable.Range(10, 10).ToArray();
This one will create an array with integers 10 to 19.
For some real life problems, I need to use the index of the original data.
After some research, I found that I can do something like this
var multipliedArray = arrayIndex.Select((i, Index) => i * Index).ToArray();
I know that i is the item itself, in this case i will be integer.
So, just two questions
How do I know the full list of parameters that can put within the bracket (like the Index).
What's the other use case for having different parameter in the bracket.
The part within the Select...
(i, Index) => i * Index
...is lambda expression, which is equivalent to an anonymous method. If you would write the method non-anonymously, it would look like this:
int Calculate(int i, int Index) {
return i * Index;
}
When you want to pass a method as an argument, the respective parameter needs to be a delegate that matches the method's signature. The given Calculate nethod and, since they are sharing the same signature, your lambda expression match the signaturee of the Func<int, int, int> delegate. As it turns out, Enumerable.Select<int, int>offers you an overload with exactly this delegate, so you can use your lambda expression. The other (more widely used) overload accepts a Func<int, int>, which is the version without the index. There are no other overloads, so you can not have other arguments in your lambda expression.
For a better understanding, you can refer to the relevant document Or using Code Completion in development environments.
I have this code and I understand that it's sorting the list lstDMV. But please help me break it down.
lstDMV.Sort((x, y) => DateTime.Compare(x.NotifDate, y.NotifDate));
What does => mean? And how does it work based on the integer returned from the compare function?
How can I sort my lstDMV if I'm sorting integers instead of dates?
It's called lambda expression.
For the comparison itself, do have a look at the DateTime.Compare method. See its return values:
< 0 --> t1 is earlier than t2
0 --> t1 is the same as t2
> 0 --> t1 is later than t2
The lambda operator => in
lstDMV.Sort((x, y) => DateTime.Compare(x.NotifDate, y.NotifDate));
basically creates a new delegare with a block of code to excecute. The x and y is past along as parameters.
you could sort a list of int by changing the code to
lstDMV.Sort((x, y) => x.CompareTo(y));
It is called lambda operator. From MSDN;
The => token is called the lambda operator. It is used in lambda
expressions to separate the input variables on the left side from the
lambda body on the right side. Lambda expressions are inline
expressions similar to anonymous methods but more flexible; they are
used extensively in LINQ queries that are expressed in method syntax.
For sorting operation, use Sort() method like this;
lstDMV.Sort((int1, int2) => int1.CompareTo(int2));
=> is a lambda expression operator you can think of it as an anonymous function in javascript
in this case
lstDMV.Sort((x, y) => DateTime.Compare(x.NotifDate, y.NotifDate));
it is creating a function that is being used as the handler for Sort event.
The complier can infer the types of x and y since it knows the defintion of Close delelegate.
First of all, these are Lambda-Expressions.
Now to your question:
=> is an operator that defines the return value.
In your case (x,y) will return the value of DateTime.Compare(x.NotifDate, y.NotifDate).
Now the Sort()- function of your List will somehow sort the List depending on the value of DateTime.Compare(x.NotifDate, y.NotifDate).
Take a look at the MSDN article: http://msdn.microsoft.com/en-us/library/bb397687.aspx
It's very helpful.
(Others have already answered the lambda operator part of your question)
how can i sort my lstDMV if i'm sorting integers instead of dates?
ints.Sort((i1, i2) => i1.CompareTo(i2));
Consider this code fragment;
int sum = 0;
sum = Expression.Evaluate("1+1");
where the value of sum = 2
I do have an expression that will compute values but i want that expression to be build programatically then evaluate the result. I don't have any idea what class or namespace that I will dealing with. Anyone can help me.
You could use Expression Trees:
Expression trees represent code in a tree-like data structure, where
each node is an expression, for example, a method call or a binary
operation such as x < y.
You can compile and run code represented by expression trees.
Expression Trees (C# and Visual Basic)
Expression Tree Basics
Note: This problem can be solved using System.Reflection.Emit and work directly with MSIL, but the resulting code is hard to write and read.
After a little browsing, I suggest you checkout Flee on Codeplex: Fast Lightweight Expression Evaluator :
Flee is an expression parser and evaluator for the .NET framework. It
allows you to compute the value of string expressions such as sqrt(a^2
+ b^2) at runtime. It uses a custom compiler, strongly-typed expression language, and lightweight codegen to compile expressions
directly to IL. This means that expression evaluation is extremely
fast and efficient.
You can build Expressions trees either using lambdas or by building them programatically using classes in the System.Linq.Expressions namespace.
See MSDN for more info.
Have you seen http://ncalc.codeplex.com ?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");
e.Parameters["Pi2"] = new Expression("Pi * Pi");
e.Parameters["X"] = 10;
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "Pi")
args.Result = 3.14;
};
Debug.Assert(117.07 == e.Evaluate());
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.
It also supports logical operators, date/time's strings and if statements.
I want to evaluate a math expression which the user enters in a textbox. I have done this so far
string equation, finalString;
equation = textBox1.Text;
StringBuilder stringEvaluate = new StringBuilder(equation);
stringEvaluate.Replace("sin", "math.sin");
stringEvaluate.Replace("cos", "math.cos");
stringEvaluate.Replace("tan", "math.tan");
stringEvaluate.Replace("log", "math.log10");
stringEvaluate.Replace("e^", "math.exp");
finalString = stringEvaluate.ToString();
StringBuilder replaceI = new StringBuilder(finalString);
replaceI.Replace("x", "i");
double a;
for (int i = 0; i<5 ; i++)
{
a = double.Parse(finalStringI);
if(a<0)
break;
}
when I run this program it gives an error "Input string was not in a correct format." and highlights a=double.Parse(finalStringI);
I used a pre defined expression a=i*math.log10(i)-1.2 and it works, but when I enter the same thing in the textbox it doesn't.
I did some search and it came up with something to do with compiling the code at runtime.
any ideas how to do this?
i'm an absolute beginner.
thanks :)
The issue is within your stringEvaluate StringBuilder. When you're replacing "sin" with "math.sin", the content within stringEvaluate is still a string. You've got the right idea, but the error you're getting is because of that fact.
Math.sin is a method inside the Math class, thus it cannot be operated on as you are in your a = double.Parse(finalStringI); call.
It would be a pretty big undertaking to accomplish your goal, but I would go about it this way:
Create a class (perhaps call it Expression).
Members of the Expression class could include Lists of operators and operands, and perhaps a double called solution.
Pass this class the string at instantiation, and tear it apart using the StringBuilder class. For example, if you encounter a "sin", add Math.sin to the operator collection (of which I'd use type object).
Each operator and operand within said string should be placed within the two collections.
Create a method that evaluates the elements within the operator and operand collection accordingly. This could get sticky for complex calculations with more than 2 operators, as you would have to implement a PEMDAS-esque algorithm to re-order the collections to obey the order of operations (and thus achieve correct solutions).
Hope this helps :)
The .Parse methods (Int.Parse, double.Parse, etc) will only take a string such as "25" or "3.141" and convert it to the matching value type (int 25, or double 3.141). They will not evaluate math expressions!
You'll pretty much have to write your own text-parser and parse-tree evaluator, or explore run-time code-generation, or MSIL code-emission.
Neither topic can really be covered in the Q&A format of StackOverflow answers.
Take a look at this blog post:
http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
It sounds like it does pretty much what you're trying to do. Evaluating math expressions is not as simple as just parsing a double (which is really only going to work for strings like "1.234", not "1 + 2.34"), but apparently it is possible.
You can use the eval function that the framework includes for JScript.NET code.
More details: http://odetocode.com/code/80.aspx
Or, if you're not scared to use classes marked "deprecated", it's really easy:
static string EvalExpression(string s)
{
return Microsoft.JScript.Eval.JScriptEvaluate(s, null, Microsoft.JScript.Vsa.VsaEngine.CreateEngine()).ToString();
}
For example, input "Math.cos(Math.PI / 3)" and the result is "0.5" (which is the correct cosine of 60 degrees)
List<int> result1 =
(from number in list where number < 3 select number).ToList();
List<int> result2 = list.Where(n => n<3).ToList();
What's the difference between these two different statements?
The first notation is usually called "query syntax", the second one "method syntax" (or dot notation, or lambda syntax) - both are compiled down to exactly the same code, but as already mentioned usually one of the two is more succinct, for most scenarios this is the dot notation but especially for joining or grouping over multiple enumerations query syntax really shines.
Also check out LINQ Query Syntax versus Method Syntax (C#):
Most queries in the introductory LINQ
documentation are written as query
expressions by using the declarative
query syntax introduced in C# 3.0.
However, the .NET common language
runtime (CLR) has no notion of query
syntax in itself. Therefore, at
compile time, query expressions are
translated to something that the CLR
does understand: method calls. These
methods are called the standard query
operators, and they have names such as
Where, Select, GroupBy, Join, Max,
Average, and so on. You can call them
directly by using method syntax
instead of query syntax.
In general, we recommend query syntax
because it is usually simpler and more
readable; however there is no semantic
difference between method syntax and
query syntax.
Nothing.
The first one uses LINQ notation, while the second one uses extension method notation -- they both do the same thing.
Use whatever looks more pleasing to you. :)
There is no difference. One is just a language extension that looks similar to SQL instead of using delegates to achieve the same result.
You notice already the first is LINQ notation and the second one uses extension method with lambda. Use the second for less code maintainance. but if you think the similarity of internal code or performance, simply use stop watch and run this code 100000 times and choose the fastest one. If the compiled code is similar, you will get the time almost the same.