Dynamic LINQ filter - linq

I am using System.Linq.Dynamic and I have following piece of code.
var filter = "Id==1 AND Id==2 AND ID==3";
var docs= context.Documents.Where(filter);
Above code works .
I want to change it to something like
var filter = "(new int[]{1,2,3}).Contains(Id)";
var docs= context.Documents.Where(filter);
Is it possible ?

System.Linq.Dynamic documentation says:
The expression language supports integer, real, string, and character literals.
So Array literals are not supported.
Also, Contains is not listed as being supported.
See the Dynamic Expressions documentation.

Related

Fetch value from XML using dynamic tag in ESQL

I have an xml
<family>
<child_one>ROY</child_one>
<child_two>VIC</child_two>
</family>
I want to fetch the value from the XML based on the dynamic tag in ESQL. I have tried like this
SET dynamicTag = 'child_'||num;
SET value = InputRoot.XMLNSC.parent.(XML.Element)dynamicTag;
Here num is the value received from the input it can be one or two. The result should be value = ROY if num is one and value is VIC if num is two.
The chapter ESQL field reference overview describes this use case:
Because the names of the fields appear in the ESQL program, they must be known when the program is written. This limitation can be avoided by using the alternative syntax that uses braces ( { ... } ).
So can change your code like this:
SET value = InputRoot.XMLNSC.parent.(XMLNSC.Element){dynamicTag};
Notice the change of the element type as well, see comment of #kimbert.

Linq to XML + chaining expressions

I have the following code that's repeated:
var ccaNumber = (from r in xDoc.Elements("ResultSet").Elements("DataRow")
where Convert.ToInt32(r.Element("PaymentPlanNumber").Value) == payPlan.OrderNumber
Ideally, I want to create the above as an expression then add my clause to the end of it.
So, I created the expression as follows:
Expression currExp = from r in xDoc.Elements("ResultSet").Elements("DataRow")
where Convert.ToInt32(r.Element("PaymentPlanNumber").Value) == payPlan.OrderNumber;
I now want to combine them:
var ccaNumber = (currExp select r.Element("CreditCardAuthorityNumber").Value).FirstOrDefault();
However I now get the following error:
Invalid expression term ')'
Any suggestions?
ta,
yogi
I think you are mixing things up here.
What you can do is:
var items = from r in xDoc.Elements("ResultSet").Elements("DataRow")
where Convert.ToInt32(r.Element("PaymentPlanNumber").Value) == payPlan.OrderNumber
select r;
This declares items as a Enumerable of elements that match your Where-Condition.
And then you can use those defined items like this:
var ccaNumber = items.Select(item=>item.Element("CreditCardAuthorityNumber").Value).FirstOrDefault();
However, this is all utilising lazy evaluation and you need to take care of multiple enumerations here. Here is a pretty indepth explanaition that is way better than my sh*tty english.
When adding to an existing expression, you need to use the lambda syntax, not the Linq syntax:.
Try:
var ccaNumber = (currExp
.Select(r=>r.Element("CreditCardAuthorityNumber").Value))
.FirstOrDefault();

How to query a Mongoid Regexp Field?

I want to create a regex field in my Mongoid document so that I can have a behavior something like this:
MagicalDoc.create(myregex: /abc\d+xyz/)
MagicalDoc.where(myregex: 'abc123xyz')
I'm not sure if this is possible and what kind of affect it would have. How can I achieve this sort of functionality?
Update: I've learned from the documentation that Mongoid supports Regexp fields but it does not provide an example of how to query for them.
class MagicalDoc
include Mongoid::Document
field :myregex, type: Regexp
end
I would also accept a pure MongoDB answer. I can find a way to convert it to Mongoid syntax.
Update: Thanks to SuperAce99 for helping find this solution. Pass a string to a Mongoid where function and it will create a javascript function:
search_string = 'abc123xyz'
MagicalDoc.where(%Q{ return this.myregex.test("#{search_string}") })
The %Q is a Ruby method that helps to escape quotes.
regexp is not a valid BSON type, so you'll have to figure out how Mongoid represents it to devise a proper query.
Query String using Regex
If you want to send MongoDB a regular expression and return documents MongoDB provides the $regex query operator, which allows you to return documents where a string matches your regular expression.
Query Regex using String
If you want to sent Mongo a string and return all documents that have a regular expression that matches the provided string, you'll probably need the $where operator. This allows you to run a Javascript command on each document:
db.myCollection.find( { $where: function() { return (this.credits == this.debits) } } )
You can define a function which returns True when the provided string matches the Regex stored in the document. Obviously this can't use an Index because it has to execute code for every document in the collection. These queries will be very slow.

How do I use a guid in a mongodb shell query

When using the MongoDB shell, how do I use a guid datatype (which I have used as the _id in my collection).
The following format doesn't work:
>db.person.find({"_id","E3E45566-AFE4-A564-7876-AEFF6745FF"});
Thanks.
You can use easily:
.find({ "_id" : CSUUID("E3E45566-AFE4-A564-7876-AEFF6745FF")})
You have to compare the _id value against an instance of BinData (not against a string). Unfortunately the BinData constructor takes a Base64 string instead of a hex string.
Your GUID value is missing two hex digits at the end, so for the purposes of this example I will assume they are "00". The following values are equivalent:
hex: "E3E45566-AFE4-A564-7876-AEFF6745FF00" (ignoring dashes)
base64: "ZlXk4+SvZKV4dq7/Z0X/AA=="
So your query should be:
>db.person.find({_id : new BinData(3, "ZlXk4+SvZKV4dq7/Z0X/AA==")})
I am assuming that the binary subtype was correctly set to 3. If not, what driver was used to create the data?
You could use the following js function in front of your query like so:
function LUUID(uuid) {
var hex = uuid.replace(/[{}-]/g, ""); // removes extra characters
return new UUID(hex); //creates new UUID
}
db.person.find({"_id" : LUUID("E3E45566-AFE4-A564-7876-AEFF6745FF"});
You could save the function in .js file and load it or open it before you make your query and if you copy the value from your results you should rename the function with:
LUUID for Legacy UUID
JUUID for Java encoding
NUUID for .net encoding
CSUUID for c# encoding
PYUUID for python encoding
I know it's an old issue, but without any additional needs you can use this one:
find({_id:UUID('af64ab4f-1098-458a-a0a3-f0f6c93530b7')})
You can fix this issue by using split() and join() workaround:
for instance if I use "E3E45566-AFE4-A564-7876-AEFF6745FF" hex value with - inside UUID() function, it does not return BinData in mongo so please try removing all the - before passing to UUID function.
db.person.find({"_id":UUID("E3E45566-AFE4-A564-7876-AEFF6745FF".split("-").join(''))});
Or by defining a variable to do it in multiple line:
var uuid = UUID("E3E45566-AFE4-A564-7876-AEFF6745FF".split("-").join(''))
db.person.find({"_id":uuid});
or by creating a simple function:
function BUUID(uuid){
var str = uuid.split("-").join('');
return new UUID(str);
}
db.person.find({"_id": BUUID("E3E45566-AFE4-A564-7876-AEFF6745FF")}).pretty();

What are the names given to these 2 LINQ expressions

I'm trying to find the correct names for these 2 "types" of coding expressions in LINQ so that I can refer to them correctly. I want to say that the first is called "Fluent Style"?
var selectVar = arrayVar.Select( (a,i) => new { Line = a });
var selectVar =
from s in arrayVar
select new { Line = s };
First - calling an extension method.
This style of coding is called "fluent interface" as you mentioned.
Second method is called language integrated query
The name of the second form is "query comprehesion syntax", which the compiler translates into the first form.
The first isn't even really LINQ, it's a lambda expression, with a type invariant object created.
(a) => new { blah = b}
The second is a LINQ query filling an on the fly class that has a property Line.
There is no hashrocket operator in this one, so this one is just plain old linq.

Resources