How can I compare lower case column values from string value which is in lower case - c#

I need to compare a lower case column value with lower case value which I am passing for comparison. I want this query using predicate builder expression.
For eg:
Context.customer.where(x=>x.name.ToLower() == name.ToLower);
I want to convert these expression into dynamic predicate builder expression. Anyone have idea please paste it.
I want to convert above linq these expression into dynamic predicate builder expression. Anyone have idea please paste it.

Related

NCalc expression validation

How can I validate NCalc expression? I want to use NCalc for evaluating if/else/endif condition in my simple custom language for defining sequence of steps. Main program will provide some parameters for conditions. Sequences are defined by user, so my parser have to validate if condition is ok and uses only provided parameters.
I already tried some tests, but don't know how to do this. HasErrors() methods doesn't check used parameters. Evaluate() uses optimalizations, so if I write expression "true or XXXX", it will end with true result and doesn't find out that XXXX parameter is invalid. How can I do this? I want to validate it already in compilation time.
Thanks.
I found the answer in this question (marked as answer), maybe I should have used also other keywords in google.
Get the parameters in an expression using NCalc
I tested that solution with my visitor based on LogicalExpressionVisitor and it's working. But, theoretically, maybe it's not the same as validation, because I get the list of parameter names, but from parsed expression, without supplied parameter values. So maybe the expression can fail in case of special "bad" parameter values supplied for evaluation. But it's enough for my case, I know all parameters I will supply to expression, so for me it's enough to get just parameter names.

Regular Expression between Ranges

Having a method that takes an amount as an argument and return after comparing with Range{minRange, maxRange} like {5,100} or {100,500} etc
Trying to construct a regular expression that will validate that Input amount is in between Range of {5,100} or {100,500} or {200,2000}.
Note: MinRange & MaxRanges values are changes after some constant interval of time.
Please advise
Following regular expression can be used to validate/verify that the given input is in-between Ranges
^(?:[5-9]|[1-9][0-9]{1,2}?|1000)$

Regular Expression matching using Lambda Expressions

I am trying to implement a wildcard search Functionlity for (*,?) using LINQ to SQL. As of now, I want to try it using Regular expression as the code we write will be short and easily manageable. Here is what I have
string kw=_keyword.Replace("*",".*").Replace("?",".");
var predicate = PredicateBuilder.True<DAL.RequestAttribute>();
Regex reg=new Regex("^"+kw+"$");
predicate=predicate &&(reg.IsMatch(ra=>ra.AttributeValue));
So, here it gives a compilation error as "Cannot convert lambda expression to type 'string' because it is not a delegate type"
Though some workarounds if I make it compile and run, I get this runtime Error
"Method 'Boolean IsMatch(System.String)' has no supported translation to SQL."
So, I have two Questions here
1. Am I thinking in right lanes to implement my wildcard using Regular Expressions? if not, which is more efficient way to do this?
2. How to resolve this error .
Thanks
You could mimic SQL's LIKE operator by using SqlMethods.Like: https://msdn.microsoft.com/en-us/library/system.data.linq.sqlclient.sqlmethods.like%28v=vs.110%29.aspx.
Just be sure to use the appropriate wildcards/tokens: https://msdn.microsoft.com/en-us/library/ms179859.aspx.
Update:
You cannot use regular expressions with simple SQL. Since you are essentially building a SQL statement via LINQ, the same rule applies. Though, it's still not quite clear where you are tapping into LINQ with the sample code you've provided.
I would typically expect to see something like the following:
var results =
from Something in SomeLinqContext
where SqlMethods.Like(Something.Value, kw);
After some research I found an answer to my question. Thanks to Ventaur for the Suggestion. the solution is on similar lines but just a bit different. PFB the code for it
string kw=_keyword.Replace("*","%").Replace("?","_");
var predicate = PredicateBuilder.True<DAL.RequestAttribute>();
predicate = (ra => SqlMethods.Like(ra.AttributeValue, kw) && <Any other boolean conditions>
Therefore it boils down to how to make an expression out of SQLMethods.like method using our predicate builder class.

How to convert a search string to a boolean condition?

I have a search criteria stored in a string:
string Searchstr = "(r.Value.Contains("PwC") || (r.Value.Contains("Canadian") && r.Value.Contains("thrive"))) || (r.Value.Contains("Banana") && r.Value.Contains("Gayle"))"
I want to use this in a If statement to check the values:
if(searchstr)
{
then do this....
}
but the if should have a searchstr as boolean.
How to convert this to boolean?
EDIT: The requirement is to give search criteria dynamically in a text box in the following format - "PwC OR (Canadian AND thrive)".
Which will be used to search an XML file.
Therefore I have loaded an XML file and want to have a Where condition in LINQ for which I need to use Dynamic LINQ but string is not allowed in that and also I have some braces to deal with.
Thinking of that I have taken the resultset from the XML(The tag value which i need to search)
var selectedBook = from r in document.Root.Descendants("Archives").Elements("Headline").Elements("Para")
select r;
and would ideally like to try something like:
var query=selectedbook.Where(searchstr)
OR
if(searchstr){....then do this}
You will need to do a bit of work to make this happen, but it is possible.
You should have a look at the dynamic LINQ library. This allows you to specify LINQ conditions (and other clauses) as strings and execute them just like LINQ operators.
Start with the explanation on ScottGu's blog and follow the links:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
I'm assuming the string is going to reference only a specific set of objects (r or r.Value in this case, for example - or anything else you want, as long as you know it beforehand). If this is the case, then:
Create a delegate that takes the objects (that may be referenced) as parameters
and returns a bool, as you want.
Programmatically write a small C# source file in memory that defines the query
as the body of a method (with a fixed name, preferably) that conforms to the delegate specified above.
Use the CSharpCodeProvider class to compile an assembly
with your custom function that returns the bool you want.
Run the dynamically written and compiled code from your main program.
Well as you may guess it is not going to be straight forward but at the same time it is not as hard a problem as it seems
You can perform a few steps to get what you want:
Get the search expression as input (for e.g. "PwC OR (Canadian AND thrive)")
Write an extension method on XElement that returns true and takes the search criteria as input. You will then be able to use
var selectedBook = from r in
document.Root.Descendants("Archives").Elements("Headline").Elements("Para")
where r.SatisfiesCriteria(searchCriteria)
select r;
Write a parser class that parses searchCritera and stores it in parsed format. (for e.g. you can convert it into postfix notation). This is quite easy and you can use standard algorithm for this. For your purpose OR, AND will be operators and PwC etc. will be operands. Parenthesis will get removed as part of parsing.
Now simply invoke this parser from with in your extension method and then evaluate the postfix expression you get. This again can be done through standard stack based evaluation. Infact it would be better if you parse the criteria once and then only evaluate in where. While evaluating you need to replace the operands with r.Value.Contains
It seems like a good scenario for http://scriptcs.net/

Please explain what's going on in this part of the C# code using line => line and .toArray

Here's the code:
File.ReadLines(sourceFilePath).Select(line => line.Split('\t')).ToArray();
I get what's going on up until the "Select" keyword. Can someone please break down what is going on in "line => line.Split...
My understanding is that we are going line by line through the text file and parsing and splitting a line of input text by tabs (since I know the text is tab-delimited). But, what exactly is going on with "line => line..."?
And I get at the end of the line of code the text is going into an Array. But when I debug and step through the code and use the locals window what is the name of the Array that contains what has been read? How do I see what is read into the Array?
This is saying, essentially, "For each line in the file, split the line on the tab character into an array of strings, then create an array of those arrays (such that each element in the returned array is an array)"
The Select function takes an Enumerable of something and applies a function to each item, producing 1 output value for each input value. In other programming languages this is called a Map or a Projection.
The => indicates a lambda expression which is compiled into a delegate function. It takes an argument called "line", whose type is inferred by the usage (because ReadLines returns an IEnumerable of Strings, line is of type String).
The lambda's body has an implied return type of the value resulting from the last call (the call to Split). Thus, the line says "run this lambda on each line".
Finally, the call to .ToArray at the end (outside of the lambda) converts the IEnumerable<String[]> returned by Select into an array of arrays (String[][]).
The => is a lambda expression - think of it as a type of delegate or as an Function. Each item that is returned from File.Readlines is operated on by the Select - the Select passes each line through the lambda function line => line.Split('\t') which takes a single argument (named line) and then returns the result of calling .Split('\t') on the line argument.
The Select operator is a LINQ extension method used to handle projecting elements from a collection into a different form. The most common usage would be to select a single column from the elements of that collection into a new collection, however more complex projections can be handled inside the lambda expression.
The compiler automatically infers the datatype returned by the Select method so that its dependent on whatever the output is of the lambda you pass in. In your case, the output of the lambda is an Array of strings, so ultimately it returns an IEnumerable<string[]>. When you call ToArray() at the end, you then convert the IEnumerable<string[]> into a concrete string[][].
This is Linq.
The Select method is an extension on IEnumerable, it lets you 'project' each result into some other form using a lambda expression (the line => ... part)
In this case, the developer wants to split each line on the tab character (resulting in an array, this is the projection) and retrieve an array containing each result.

Categories