Extract predicate from expression tree [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
HI Having that Linq query
services.Get<Container>().Where(x => x.Approval.Status == "APPROVED")
How do I get Approval.Status == "APPROVED"

This is MUCH harder to do than it seems. If the Where method is yours, and your parameter type is Expression<Func<T, bool>>, you can get the predicate as easy as myExpression.Body.
But all you'll get out of that is an Expression, which could be literally anything. You own example is a binary expression of a member expression of a member expression of a parameter expression comparing against a Constant Expression. What happens if you call a method? Like this:
services.Get<Container>().Where(x => x.IsStatus("APPROVED"))
It'll result in a completely different expression that'll require completely different handling than in your example. Even if you don't permit method calls, you still have to parse the expression to confirm it isn't one.
And because Expressions aren't language specific, ToString() can be pretty unpredictable. It's like halfway between IL and C#.
Pretty much all you can do is build an expression parser, which is quite the undertaking. If this is something you want to delve into, check out ExpressionVisitor. It provides a convenient way to iterate over and parse an Expression as you need to.

Related

using a function inside a lamba expression [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
To manage rounding there are usually two methods, the first method is round values then to sum them. Or sum values then to round them. Of course to the required precision that you want.
I want to go with the first method and I need to update this line that currently do the opposite.
this.ClonedEntity.MontantHT = ArroundDecimal.CustomDecimalArround(correctedLines.Sum(l => l.MontantHT ?? 0));
When I try to call my static method in the lambda expression it doesn't work.
How would you suggest to do it while keeping use of the linq syntax ?
Thank you.
You could try something like this:
this.ClonedEntity.MontantHT = correctedLines
.Select(x=>ArroundDecimal.CustomDecimalArround(x.MontantHT ?? 0))
.Sum();
something = correctedLines.Sum(l => ArroundDecimal.CustomDecimalArround(l.MontantHT ?? 0))

is nested Linq faster than foreach loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is this "better", faster or easier to read:
var viewsOnSheet = templateSheet.GetAllViewports()
.Select(x => doc.GetElement(x))
.Cast<Viewport>()
.Select(x => doc.GetElement(x.ViewId))
.Cast<View>();
...than this:
foreach (ElementId id in templateSheet.GetAllViewports())
{
Viewport vp = doc.GetElement(id) as Viewport;
View v = doc.GetElement(vp.ViewId) as View;
}
They both work, I am just curious if there is some programming standard that I would be violating with so many nested Linq calls. What's easier to understand? I am personally leaning towards the foreach loop.
Thanks!
For Linq-to-objects, code with foreach is always marginally faster that equivalent LINQ call just because at the end LINQ end up with similar foreach after several method calls. For Linq-to-SQL/Linq-to-XML equivalent code with less function calls would be faster too just because you execute less code.
Note that proper matching code for more complex LINQ expressions may not be easy to write (try writing GroupBy yourself correctly) and definitely will not be shorter than LINQ.
Whether this performance different matters for your application - measure yourself against your particular performance goals.
Style of code is strictly personal preference - pick whatever works for you/your team.

How to use Enumerable Methods [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have looked around for some good explanations of these enumerable methods but cant seem to find one that explains it properly.
I have been using a few of them like select,skip,orderby and sort but I don't know how they actually work
For example
string[] RandomNames = names.OrderBy(x => rnd.Next()).ToArray();
or
string[] SelectedNames = names.Select(i => i.ToString()).ToArray()
So there are a few things that I am unclear of:
So what does the => actually do
How would a group by work and what would it be used for.
A brief explanation would be appreciated but an in depth explanation is what I am looking for.
=> is lambda expression.
What is lambda expression and why is so useful? Let's consider example:
You have list of random integers and you want to choose only divided by 2. In normal way it will look like that:
public bool IsDevidedByTwo(int number)
{
if(number % 2 == 0)
return true;
return false ;
}
List<int> DevidedByTwoList = new List<int>;
foreach(var number in RandomIntsList)
{
if(IsdevidedByTwo(number)) DevidedByTwoList.Add(number);
}
It easy an clear but takes lot of space so you can't understand it immediatly especially when function IsDevidedByTwo() will be in diffrent file.
How it will be look like when you use lamba expression and LINQ:
List<int> DevidedByTwoList = RandomIntsList.Where(number => number % 2 == 0).ToList();
One line instead of 12.
number => number % 2==0 is lambda expression. It's check if number is devided by 2. It works exacly like IsDevidedByTwo function but you don't need to name it.
.Where() is LINQ method witch can filter for example list and choose only elements fulfill condition in brackets.
If you want to learn more read something about LINQ and lambda expresions.
A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name.
It Reduces typing. No need to specify the name of the function, its return type, and its access modifier.When reading the code, you don't need to look elsewhere for the method's definition.
Here is a very good article with examples and explanations.
geekswithblogs

Need a expression to pass as parameter in c# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using a external DLL as reference.
When i try to consume a method its asking for a expression as a parameter to filter the results.
Its expecting the type as follows
Expression<Func<Template, bool>> type as a parameter.
The template type has name and group id as properties.
I am trying to create an expression that will check if the object is equal to the group id and if the name contains in a list of items as follows.
Expression<Func<Template, bool>> filterTemplatesDestination = tmplt =>
stselectedTemplates.Contains(tmplt.Name) &&
tmplt.TemplateGroupId == stDestGroupID;
But when i assign this expression to the method i am getting an exception. If i use just the group id to filter it work fine. The expression is throwing exception when i use condition to check if the name exists in my condition.
I guess you get a NullReferenceException, I don't see any other possible exception in your code. Try this:
Expression<Func<Template, bool>> filterTemplatesDestination = tmplt =>
(stselectedTemplates!= null && tmplt.Name!=null && stselectedTemplates.Contains(tmplt.Name)) &&
tmplt.TemplateGroupId == stDestGroupID;
It seems as though your stselectedTemplate OR your tmplt.Name is null, I would take the Paolo Costa's answer and instead check for both null exceptions, but it may be better to debug your code and find exactly why those variables are returning null.

Which one is more efficient in performance, "x>=a" or "x>a || x==a"? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I don't know the internal implementation of the following. Shortly speaking, which one is more efficient in performance, x>=a or x>a || x==a?
Edit 1:
Let's divide it into 2 cases:
when both a and x are in the same type.
when a and x are not in the same type.
Strictly speaking, they're not equal. The operators could be overloaded to do entirely different things. Speaking to their performance is only relevant if they are functionally identical.
They are also functionally different in that the expressions x and a are evaluated multiple times, rather than once, in the second example. (Credit to Kirk's comment mentioning this.) If these expressions cause side effects, or are expensive to compute, that can be relevant to either their functional or performance characteristics.
We also can't really speak to their performance at all without knowing the specific type. Some types could have radically different performance characteristics for these operators than some other type. I could be mean and throw a Thread.Sleep(1000) in my >= operator, just because.
When x and a are primitives, good chances are that the optimizer will convert both to the same code. However, when x and a are complex expressions with function calls, and the "less than" expression returns false in considerable percentage of the cases, you will see the expression with "less than or equals" perform faster. In addition, the first expression is branchless, while the second one has a branch.
Your expression is already fully reduced. There is no way to write x >= a that requires fewer than 1 comparison operation, which is what it does now.

Categories

Resources