How parse a string as linq exprssion? - string

I've this linq to devforce expression :
(from r in mgr.testTables select r).OrderBy(r => r.id);
I want to specify sorting column name as a string, I need something like this :
string orderBy = "r => r.id";
(from r in mgr.testTables select r).OrderBy( orderBy );
is there any way to parse a string as linq expression ?

There's a sample of a fully operational expression parser that will actually do this for you based on a string in C# Samples for Visual Studio 2008 at MSDN Code Gallery, under DynamicQuery. (The LinqDataSource control uses a slightly modified version of this sample internally.)

One option is to use Dynamic LINQ project for this. I think this is the same thing as DynamicQuery mentioned by Ruben. Anyway, it allows you to write things like:
var res = db.Table.Where("CategoryID == 2").Select("CategoryName");
Dynamic LINQ adds overloads of the usual LINQ methods that take string as parameters. They parse the string into an expression tree that can then be used by LINQ or LINQ to SQL.
An alternative is to compose the expression tree from simple pieces of code (such as functions that access various properties and various operators that you can use to compare them against values). I think this is more elegant and involves less overhead. I wrote about this approach here and there is a type named PredicateBuilder that makes it simpler.

Related

Dynamically check extensions from string in Reactive Extensions

I have string with accepted file's extensions. Something like "JPG,PNG,TXT". String can be whatever I want. I am using Reactive Extensions, so i filter files by using Where(). For now i am using
Where(e => e.FullPath.Contains(filtering)
But it only works, when there is only 1 extension. Any idea how to make it dynamically? Where will be call only once! I write in c#.
This looks to be a LINQ question rather than javascript(rxjs). However, as LINQ seems to be comparable with array methods in js I shall attempt to answer.
First convert the string of extensions into an array. This only needs to be done once:
filterExtensions = filtering.Split(',');
Then the condition would be:
Where(e => filterExtensions.Any(
extension => e.FullPath.Contains(extension)
))

Regex or IndexOf?

I have a long string "AB100123485;AB10064279293-IP-1-KNPO;AB473898487-MM41". I have to extract integer value after "IP-" i.e 1 (only) what is the most efficient way ? I am using c#
Thanks
The 'most-efficient' way depends on how consistent your string is in terms of length and appearance. You can surely do this with a regular expression as a quick solution if you just want to get the digit directly following IP-.
You can utilize the RegularExpressions API, passing in your regular expression and input string.
https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.match?view=netframework-4.8#System_Text_RegularExpressions_Regex_Match_System_String_System_String_
This pattern should get you started IP-[0-9]; refine it more to your use case as needed.
For example:
Match matched = System.Text.RegularExpressions.Match(
"AB100123485;AB10064279293-IP-1-KNPO;AB473898487-MM41",
"IP-[0-9]"
);

Looking up a list of words into a String in Scala

I need to find if any word from a word list (which could be a Set or List or another structure) is contained (as a sub-string) in another String and I need the best possible performance.
This could be an example:
val query = "update customer set id=rand() where id=1000000009;"
val wordList = Set("NOW(", "now(", "LOAD_FILE(", "load_file(", "UUID(", "uuid(", "UUID_SHORT(",
"uuid_short(", "USER(", "user(", "FOUND_ROWS(", "found_rows(", "SYSDATE(", "sysdate(", "GET_LOCK(", "get_lock(",
"IS_FREE_LOCK(", "is_free_lock(", "IS_USED_LOCK(", "is_used_lock(", "MASTER_POS_WAIT(", "master_pos_wait(",
"RAND(", "rand(", "RELEASE_LOCK(", "release_lock(", "SLEEP(", "sleep(", "VERSION(", "version(")
What is the best option to achieve the best performance? I have read about the contains method but it doesn't work for sub-strings. Is the only option to iterate through the list and to use the method indexOf or there is a better option?
For Scala collections, the method to use in order to answer a question like "is there an item in this collection that satisfies my condition?" is exists (scroll up slightly when you get there because the scaladoc pages are weird about linking directly to methods).
Your condition is "does the string (query) contain this item (word)?" For this, you can use String's contains method, which comes from Java.
Putting it together, you'll get
wordList.exists { word => query.contains(word) }
// or, with some syntax sugar
wordList exists { query.contains }
You can also use .find instead of .exists, which will return an Option containing the first match that was found, instead of just a Boolean indicating whether or not something was found.
scala> wordList.exists(query.contains)
res1: Boolean = true
scala> wordList.find(query.contains)
res2: Option[String] = Some(rand()
This is advice for solution:
Check that you need to optimize it. "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
Array is collection with fastest access to element. Use it to increase access's speed.
Sometimes use a ParArray may increase performance.
If it's acceptable, for best performance first cast string to lower case, and remove all UPPER_CASE from set.
You can use own "contains" method to find any of substring. E.g., you can group some words by their prefixes (or suffixes) and don't pass all group if next (prev) symbol is different.
Use native Java to increase performance (Scala can wrap array)
First find all positions of (, because all variants related to it. Than you can check last word's symbol.
Sorry for my English. It is not best advice, but I know small amount of people (e.g. on acm.timus.ru) which can write more faster functions at Scala.

Assigning a mathematical string expression to double variable

I have a mathematical expression in string form like:
string strExpression = "10+100+Math.Sin(90)";
I want to simply assign this expression (at run time) to a float variable (say result), so that it becomes the following code statement:
float result = 10+100+Math.Sin(90);
How can I do this?
You have to compile the expression within a syntactically correct code block. See http://devreminder.wordpress.com/net/net-framework-fundamentals/c-dynamic-math-expression-evaluation/ as an example.
Edit: Or alternatively write your own expression parser if the expression is going to be VERY simple (I wouldn't recommend this though)
You could use CS-Script to dynamically make a class with a method that you can run, if you don't want to write your own parser but rather use C# which you allready know..

SSIS: Filtering Multiple GUIDs from String Variable as Parameter In Data Flow OLE Source

I have an SSIS package that obtains a list of new GUIDs from a SQL table. I then shred the GUIDs into a string variable so that I have them separated out by comma. An example of how they appear in the variable is:
'5f661168-aed2-4659-86ba-fd864ca341bc','f5ba6d28-7283-4bed-9f11-e8f6bef225c5'
The problem is in the data flow task. I use the variable as a parameter in a SQL query to get my source data and I cannot get my results. When the WHERE clause looks like:
WHERE [GUID] IN (?)
I get an invalid character error so I found out the implicit conversion doesn't work with the GUIDs like I thought they would. I could resolve this by putting {} around the GUID if this were a single GUID but there are a potential 4 or 5 different GUIDs this will need to retrieve at runtime.
Figuring I could get around it with this:
WHERE CAST([GUID] AS VARCHAR(50)) IN (?)
But this simply produces no results and there should be two in my current test.
I figure there must be a way to accomplish this... What am I missing?
You can't, at least not using the mechanics you have provided.
You cannot concatenate values and make that work with a parameter.
I'm open to being proven wrong on this point but I'll be damned if I can make it work.
How can I make it work?
The trick is to just go old school and make your query via string building/concatenation.
In my package, I defined two variables, filter and query. filter will be the concatenation you are already performing.
query will be an expression (right click, properties: set EvaluateAsExpression to True, Expression would be something like "SELECT * FROM dbo.RefData R WHERE R.refkey IN (" + #[User::filter] + ")"
In your data flow, then change your source to SQL Command from variable. No mapping required there.
Basic look and feel would be like
OLE Source query

Resources