Linq to XML + chaining expressions - linq

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();

Related

How to create dynamic LINQ Expression with multiple binary expression conditions and a contains condition

I want to create a dynamic LINQ Expression for this kind of query
people.Where(x => x.Name="Some_Name" && x.Age>60 && x.ChildIds.Contains("Some_Id"));
What I have already done is populating my List<BinaryExpression>. The List<BinaryExpression> contains the x.Name="Some_Name" and x.Age>60.
My problem is now with the x.ChildIds.Contains("Some_Id"). What I was looking for a way to dynamically create the Contains expression, this iswhat I got:
Expression.Call(memberExpression, "Contains", null, constantExpression)
But this returns a MethodCallExpression and I couldn't append to my List<BinaryExpression>
The reason why I want to append the contains expression into the BinaryExpression is because this is how I do the && part of the LINQ
var aggregatedExpressions = binaryExpressions.Aggregate((x, y) => Expression.AndAlso(x, y));
If there's no way for me to append the Contains expression into the Binary Expression, how do I aggregate the Contains MethodCallExpression into my aggregatedExpressions so it would be written in this way?
x.Name="Some_Name" && x.Age>60 && x.ChildIds.Contains("Some_Id")
I'm closing this now. I've figure out how I'll aggregate the MethodCallExpressions
aggregatedExpressions = Expression.AndAlso(aggregatedExpressions, methodCallExpression);

Dynamic LINQ filter

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.

OR operators and Ruby where clause

Probably really easy but im having trouble finding documentation online about this
I have two activerecord queries in Ruby that i want to join together via an OR operator
#pro = Project.where(:manager_user_id => current_user.id )
#proa = Project.where(:account_manager => current_user.id)
im new to ruby but tried this myself using ||
#pro = Project.where(:manager_user_id => current_user.id || :account_manager => current_user.id)
this didnt work, So 1. id like to know how to actually do this in Ruby and 2. if that person can also give me a heads up on the boolean syntax in a ruby statement like this altogether.
e.g. AND,OR,XOR...
You can't use the Hash syntax in this case.
Project.where("manager_user_id = ? OR account_manager = ?", current_user.id, current_user.id)
You should take a look at the API documentation and follow conventions, too. In this case for the code that you might send to the where method.
This should work:
#projects = Project.where("manager_user_id = '#{current_user.id}' or account_manager_id = '#{current_user.id}'")
This should be safe since I'm assuming current_user's id value comes from your own app and not from an external source such as form submissions. If you are using form submitted data that you intent to use in your queries you should use placeholders so that Rails creates properly escaped SQL.
# with placeholders
#projects = Project.where(["manager_user_id = ? or account_manager_id = ?", some_value_from_form1, some_value_from_form_2])
When you pass multiple parameters to the where method (the example with placeholders), the first parameter will be treated by Rails as a template for the SQL. The remaining elements in the array will be replaced at runtime by the number of placeholders (?) you use in the first element, which is the template.
Metawhere can do OR operations, plus a lot of other nifty things.

selecting an element in xml using linq extension methods

I am little new to linq and was wondering how i can select the application in the following xml based on the application name using Extension Methods (not using the query expression)
<applicationlist>
<application>
<name>test1</name>
<ele1>852</ele1
<ele2>http://localhost/test1</ele2>
</application>
<application>
<name>test2</name>
<ele1>456</ele1
<ele2>http://localhost/test2</ele2>
</application>
</applicationlist>
Assuming that by "the SQL way of selecting" you mean "using a query expression", let's start off with your query expression:
var v = from b in root.Descendants("application")
where b.Element("name").Value.Trim().ToLower() == appName.Trim().ToLower()
select b;
With extension methods, this would just be:
var v = root.Descendants("application")
.Where(b => b.Element("name").Value.Trim().ToLower() ==
appName.Trim().ToLower());
I would recommend against making case-insensitive comparisons this way though - it has cultural problems. Use something like this instead:
var v = root.Descendants("application")
.Where(b => b.Element("name").Value.Trim().Equals(appName.Trim(),
StringComparison.CurrentCultureIgnoreCase);
(or one of the other StringComparison options - or an instance of StringComparer).
You might also want to trim appName once rather than for every comparison...

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