How to do "let" in dynamic LINQ? - c#

How would I write this query in dynamic linq? I know how to do the select, but how do I do the "let"?
var qry = from sr in data.Addresses
let AddressType_Desc = sr.AddressType.AddressType_Desc
let Country_Desc = sr.Country.Country_Desc
where sr.Customer_GUID == CustomerGuid
select new
{
sr.Address_GUID,
sr.People_GUID,
sr.AddressType_GUID,
AddressType_Desc,
sr.Address1,
sr.Address2,
sr.City,
sr.State,
sr.Zip,
sr.County,
sr.Country_GUID,
Country_Desc,
sr.UseAsMailing
};

There is no equivalent of let in linq expression method syntax, as well in dynamic LINQ.
Let can only help you to make your queries more readable. It simply works as an alias or local variable. You can imagine, that in method syntax you won't be able to access it outside the scope of the method declared it.
In your case, just simply put the let variable initiation into the select.
Like this in linq method syntax:
var qry = data.Adresses.Where(sr => sr.Customer_GUID == CustomerGuid)
.Select(sr => new {
sr.Address_GUID,
....
sr.AddressType.AddressType_Desc,
sr.Country.Country_Desc
});
Or similar with dynamic LINQ (select clause as string):
var qry = data.Adresses.Where(sr => sr.Customer_GUID == CustomerGuid)
.Select("new (Address_GUID, AddressType.AddressType_Desc, Country.Country_Desc)");
And you will get the same result as with linq query syntax.
It would be similar for other expression methods. Only thing you need, is to use the value directly instead of the let alias.

Related

A query body must end with a select clause or a group clause in a Linq query using lambda expressions

I have this here Linq query using lambda expressions and its throwing an error
A query body must end with a select clause or a group clause
Here is the query in question
var query = from county in HWC.StateCounties.Where(w => w.StateID == id).Select(s => new CountyList
{
CountyID = s.StateCountyID,
CountyName = s.CountyName
});
I even tried adding a .Tolist() at the end and got the same error.
Why is this happening when I clearly have a select clause?
I made a mistake in my query, the query should be this instead
var query = HWC.StateCounties.Where(w => w.StateID == id).Select(s => new
{
s.StateCountyID,
s.CountyName
});
Although it is possible to combine Linq and extensions methods, a Linq query always needs to end with select in c# (In vb this is not necessary).
Maybe it is a matter of taste, but I prefer Linq over extension methods because it makes the code far more readable because all braces are removed.
Your query will look like
var query =
from county in HWC.StateCounties
where county.stateID == id
select new
{
county.StateCountyID,
county.CountyName,
};
If you want to combine the query will look like:
var query =
from county in HWC.StateCounties.Where(s => s.stateID == id)
select new
{
county.StateCountyID,
county.CountyName,
};

lambda equivalent to sql update with joins

I have 2 sets of data.
What would be the lambda syntax equivalent to this sql update statement ?
UPDATE Customers1
SET Customers1.Email = Customers2.Email
JOIN Customers2 ON Customers1.ID = Customers2.ID
Lambdas are just a way of writing anonymous methods: x => { body }. I assume you actually mean LINQ.
There is no equivalent, because the Q in LINQ stands for query. LINQ queries data, it doesn't change it.
As DanielHilgarth said just to use lambda or even LINQ is not enough here.
I assume you'd need something like:
foreach(var customer1 in customers1) {
var customer2 = customers2.FirstOrDefault(c2 => customer1.ID.Equals(c2.ID));
if (customer2 != null) customer1.Email = customers2.Email;
}
So, lambda is a chunk of the whole implementation.

How can i add a condition string to an sql query in an var type

Im working on an source code with an sql query in a VAR type like
var query = select ... from ... where ... ;
is it possible to add an dynamic "where clause" like
string condition = "where x.x > x.y";
e.g. var query = select ... from ... + condition;
Iam sorry for my bad english
You are not clearly stating how your query looks like. Is it a result of a LINQ operation or simply a String?
The keyword var is only usable for design time. The compiler will substitute it with the correct datatype.
If you SQL query is a string, like
var query = "Select ... from ... where ..";
then
string condition = "where x.x > x.y";
query += condition;
is valid because both variables are strings. You can't combine a non string type with a string the way your code suggests.
I do now assume that you are using a LINQ syntax. It is possible to add such conditions to a linq query per code, I think the keywords linq query builder, expression tree and predicate should get you started.
I'd strongly suggest that you stop using the var keyword without exactly knowing what it does and where to use it.
Dynamic Linq exists specifically to solve late-bound scenarios for LINQ:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Allows constructs such as:
NorthwindDataContext northwind = new NorthwindDataContext();
var query = northwind.Products
.Where("CategoryID = 3 AND UnitPrice > 3")
.OrderBy("SupplierID");
If you do not call ToList() and your final mapping to the DTO type, you can add Where clauses as you go, and build the results at the end:
var query = from u in DataContext.Users
where u.Division == strUserDiv
&& u.Age > 18
&& u.Height > strHeightinFeet
select u;
if (useAge)
query = query.Where(u => u.Age > age);
if (useHeight)
query = query.Where(u => u.Height > strHeightinFeet);
// Build the results at the end
var results = query.Select(u => new DTO_UserMaster
{
Prop1 = u.Name,
}).ToList();
This will still only result in a single call to the database, which will be effectively just as efficient as writing the query in one pass.
I saw this answer here by Reed Copsey

How can I clean up this LINQ Query (SelectMany)?

How can I clean up this LINQ Query to use SelectMany in the sql syntax, instead of method chaining at the end like I have done?
var runPeakWidths =
(from ipa in runAnalysis.PassAnalyses
let peakWidths = BuildPeakWidths(ipa)
select peakWidths)
.SelectMany(data => data);
Edit:
Turned into a tight little method:
public void CreateRunStatistics(Func<IPassAnalysis, IEnumerable<double>> buildMethod, string name)
{
var data = runAnalysis.PassAnalyses.SelectMany(buildMethod);
statistics.Add(StatisticsBase.Calc(name, data));
}
Thanks!
var runPeakWidths = runAnalysis.PassAnalyses.SelectMany(ipa => BuildPeakWidths(ipa));
You can also use this if you prefer:
var runPeakWidths = runAnalysis.PassAnalyses.SelectMany<Ipa, Pw>(BuildPeakWidths);
where Ipa is ipa's type
and Pw is PeakWidth's type.
I have been reliably informed (haven't verified myself) that return-type inference for method groups has now been implemented in the compiler, so this should work in C# 4:
var runPeakWidths = runAnalysis.PassAnalyses.SelectMany(BuildPeakWidths);
The SelectMany call can be avoided by nesting from clause in the query:
var runPeakWidths =
from ipa in runAnalysis.PassAnalyses
from peakWidth in BuildPeakWidths(ipa)
select peakWidth

Lambda Expression of Select * from TableName

I just want to know what's the lambda expression of Select * from TableName.
Like in plain LINQ it will be var res=from s in db.StudentDatas select s;
here StudentData is name of the table.
Thanks.
The lambda expression isn't needed:
var res = db.StudentDatas;
You could use one but it would be rather pointless:
var res = db.StudentDatas.Select(s => s);
The compiler will translate it to something along these lines:
db.StudentDatas.Select(s => s)
The translation to SQL is done by the Base Class Library. SQL, of course, does not use lambda expressions...
You don't require a lambda expression. You just want all members of the collection.
While both are technically correct, as in they would both give the same result in its simplistic form, this is only because the default behavior of db.table is “Select”. Behind the scenes, they are different. While one is a System.Data.Linq.Table, the other is System.Linq.IQuerable.
For example
var x = db.table ; var y= db.table(s=>s);
X = y;
would result in a compiler error.
When using the Dynamic Linq library, in cases where you have to create dynamic queries at runtime, you have to use an IQuerable as your initial select. Which means var qry = db.table(s=>s); as opposed to var qry = db.table;
Then you can go on and chain your queries like: qry = qry.Where(bla bla bla);
Found it out the hard way after a few nail biting sessions.
Code:
var allmember = eg_.table.where(x=>x).ToList();

Categories