Optional requirement on where clause in LINQ [duplicate] - sql

This question already has answers here:
LINQ to SQL Where Clause Optional Criteria
(3 answers)
Closed 8 years ago.
The goal is to build a search form that can be entered on multiple field searches. But entering all fields are optional.
What is the equivalent code in LINQ?
Thanks.
string str = "";
if(a!="")
str += "f1 == a";
if(b!="")
str += " && f2 == b";
if(c!="")
str += " && f3 == c";
select f1, f2, f3 from p
where str;

You can build up the query sequentially in the same way, something like this:
var query = someData.Items;
if (a != string.Empty)
query = query.Where(x => x.f1 == a);
if (b != string.Empty)
query = query.Where(x => x.f2 == b);
…and so on. In the end, you have built a query with only the relevant predicates.

Try
from x in p where (x.f1 == a || a == "") && (x.f2 == b || b == "") && (x.f3 == c || c == "") select new { f1 = x.f1, f2 = x.f2, f3 = x.f3 }
The or on each search variable makes it ignored when empty string. I'm assuming you already took care of nulls in a, b, c.

Related

how to get records from tempDB AX 2012 X++

I want to implement this functionality but vendBalanceProvisionalTmpProcesing is always empty, i know it is empty because it is tempDB :
while select AccountNum,PostingProfile from vendProvisionalBalanceTmpProcessing
{
select sum(AmountCur) from vendTrans
where vendTrans.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum
&& vendTrans.PostingProfile == vendProvisionalBalanceTmpProcessing.PostingProfile
&& vendTrans.TransDate >= _fromDate
&& vendTrans.TransDate <= toDate;
tempSum += vendTrans.AmountCur;
select sum(AmountMST) from vendTrans
where vendTrans.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum
&& vendTrans.PostingProfile == vendProvisionalBalanceTmpProcessing.PostingProfile
&& vendTrans.TransDate >= _fromDate
&& vendTrans.TransDate <=toDate;
tempSum+= vendTrans.AmountMST*ledgerParameters.EonExchangeRate;
tmpValue.Amount = tempSum;
tmpValue.AccountNum = vendTrans.AccountNum;
tmpValue.PostingProfile = vendTrans.PostingProfile;
tmpValue.doInsert();
}
But there are 2 scenarios where i can access to vendProvisionalBalanceTmpProcessing.AccountNum :
insert_recordset tmpValue
(AccountNum, PostingProfile, Amount)
select AccountNum
from vendProvisionalBalanceTmpProcessing
group by AccountNum
join PostingProfile, sum(AmountMST) from vendTrans
group by PostingProfile
where vendTrans.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum
&& vendTrans.PostingProfile == vendProvisionalBalanceTmpProcessing.PostingProfile
&& vendTrans.TransDate < _fromDate;
update_recordset vendProvisionalBalanceTmpProcessing
setting OpeningBalance = tmpValue.Amount
join tmpValue
where tmpValue.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum
&& tmpValue.PostingProfile == vendProvisionalBalanceTmpProcessing.PostingProfile;
Any way how i can do while select like that ?
`
I need vendProvisionalBalanceTmpProcessing.AccountNum to do two select sum over vendTrans where vendTrans.AccountNum == vendProvisionalBalanceTmpProcessing.AccountNum. So way how to do it similar to these two scenarios where i have access to vendProvisionalBalanceTmpProcessing would help me.
You would like to reread on how to link to a temporary table. Official documentation.
Especially, to access a tempDB table from outside where it is created, you need to call linkPhysicalTableInstance.

Angular 5 -> Filter "like %" (we SQL)

I have an Filter to an Array.
filter(typ: string) {
console.log("Filter");
this.nagelplattenFiltered == null;
this.nagelplattenFiltered = this.nagelplatten.filter((nagel: Nagelplatten) => nagel.Bezeichnung1 === typ);
this.nagelplatten = this.nagelplattenFiltered;
console.log(JSON.stringify(this.nagelplattenFiltered));
console.log("new: " + JSON.stringify(this.nagelplattenFiltered));
}
So we can I make a Like 'var%' we in SQL?
No you cannot. This operator doesn't exist in JavaScript. But you can use the indexOf()-method which has, used in the right way, a similar effect.
filter(typ: string) {
console.log("Filter");
this.nagelplattenFiltered == null;
this.nagelplattenFiltered = this.nagelplatten.filter((nagel: Nagelplatten) =>
nagel.Bezeichnung1.indexOf(typ) > -1);
this.nagelplatten = this.nagelplattenFiltered;
console.log(JSON.stringify(this.nagelplattenFiltered));
console.log("new: " + JSON.stringify(this.nagelplattenFiltered));
}
Your filter now delivers all Nagel-objects that contain the type-string.

Advance search in LINQ

How can i search in LINQ as stated below??
I Want to enter a string like this "a%b%c%d%" in my textbox and want result as we get in SQL.
Select *
from TableName
Where ColumnName Like 'a%b%c%d%'
LINQ doesn't have like operator, so you could first check if it contains a, b, c and d, then check if a is at start, b is before c, and c before d. Like this:
from item in context.TableName
where item.ColumnName.StartsWith("a") && item.ColumnName.IndexOf("b") != -1
&& item.ColumnName.IndexOf("c") != -1 && item.ColumnName.IndexOf("d") != -1
&& (
item.ColumnName.IndexOf("b") < item.ColumnName.IndexOf("c")
&& item.ColumnName.IndexOf("c") < item.ColumnName.IndexOf("d")
)
select item;
FROM item in context.TableName
WHERE item.ColumnName.StartWith("a%")
OR item.ColumnName.StartWith("b%")
OR item.ColumnName.StartWith("c%")
OR item.ColumnName.StartWith("d%")
SELECT item;

Filtering with Multiple DropDown Lists in MVC

I am working on 3-tier Architecture project
and I have multiple DropDown Lists to make filtering of data that is fetched from database using LINQ.
Now I need a way to filter with these dropdowns where when I select an item in any dropdown it is filtering and when I select from two dropdowns to filter by these two selections and so on...
I use linq like this:
var doctors = from d in db.Doctors
where d.CityID == id
&& d.HasSecretary == hasSec
&& d.OldSystem == oldSys
&& d.MetDoctor == metDoc
&& d.PriceProblem == priceProb
&& d.EasyToConvince == easyToCon
&& d.ComputerSavvy == comSav
&& d.Sold == sold
&& d.NotInterested == notIntr
&& d.FollowUp == followUp
&& d.NewClinic == newClin
&& d.RequestedADemo == reqDemo
select d;
And it is filtering only when I select all dropdowns, and not individually.
Please help :)
You will have to do conditional where clauses e.g.
var doctors = from d in db.Doctors;
if (id != null)
doctors = doctors.Where(d => d.CityID == id);
if (hasSec)
doctors = doctors.Where(d => d.HasSecretary == hasSec);
// other if statements
// results
var results = doctors.ToList();

Exposing SQL fired when LINQ executes

Morning all.
Just a quick one for you - where can I find the SQL that is executed when a LINQ statement fires?
I have the following code that works a treat,
var r = (from p in getproductweightsbuyer.tblWeights
where p.MemberId == memberid &&
p.LocationId == locationid
select p);
if (buyer != "Not Specified")
r = r.Where(p => p.UnitUserField1 == buyer);
if (subcategory != "Not Specified")
r = r.Where(p => p.UnitUserField2 == subcategory);
I'm just not sure of the SQL that is firing in the conditional where clause.
If you have the database context at hand you could try:
context.GetCommand(query).CommandText
if you debug your code you can put a breakpoint and analyze the value of r, which will have the actual SQL code in it.
As well as the above options, you can also run up SQL profiler and see the actual SQL sent down the wire to the DB.
If you use LINQ to SQL you can set the DataContext.Log property. This will log the SQL when you execute the query:
getproductweightsbuyer.Log = Console.Out;
var r = (from p in getproductweightsbuyer.tblWeights
where p.MemberId == memberid &&
p.LocationId == locationid
select p);
if (buyer != "Not Specified")
r = r.Where(p => p.UnitUserField1 == buyer);
if (subcategory != "Not Specified")
r = r.Where(p => p.UnitUserField2 == subcategory);
foreach (var row in r)
...