I am wondering if it is possible to turn this statement of code into a ternary if statement.
var placeHolder = await Source.EntityOrDefaultAsync<_Item>(item => item.CompanyID == order.CompanyID && item.ItemID == od.ItemID);
if (placeHolder.TaxedAllCountryRegions = true || placeHolder.TaxedFed == 1 && placeHolder.TaxedState == 1)
{
decimal.TryParse(placeHolder.HandlingFee, out decimal trueFee);
od.HandlingFee = trueFee * od.Quantity;
}
I tried formatting it like this- but don't think it quite works.
var placeHolder = await Source.EntityOrDefaultAsync<_Item>(item => item.CompanyID == order.CompanyID && item.ItemID == od.ItemID);
return (placeHolder.TaxedAllCountryRegions = true || placeHolder.TaxedFed == 1 && placeHolder.TaxedState == 1) ?
decimal.TryParse(placeHolder.HandlingFee, out decimal trueFee)
: false;
od.HandlingFee = trueFee * od.Quantity;
As canton7 already commented, you might want to use == true instead of = true. Probably
also the part after || must be embedded in parenthesis.
Apart from that, you want also assign the HandlingFee, so a conditional operator alone doesn't help. But why dont you use a bool variable?
bool computeHandlingFee = placeHolder.TaxedAllCountryRegions || (placeHolder.TaxedFed == 1 && placeHolder.TaxedState == 1);
if(computeHandlingFee && decimal.TryParse(placeHolder.HandlingFee, out decimal trueFee))
{
od.HandlingFee = trueFee * od.Quantity;
}
return computeHandlingFee;
Maybe you want to include the decimal.TryParse in the computeHandlingFee-logic.
Related
I have written a ternary condition in c# which isnt evaluating correctly. I am checking if both condition satisfy then it should return true otherwise false. At the moment it is returning true even if one condition fails. So even if the docType is Flashnotes is true, the canView is setting to true. Consider this IoC.Resolve().Authorize("Put", "ManageDocuments")
always returning true and docType may or may not return true
doc.canView = IoC.Resolve<IClientAuthorizationService>().Authorize("Put", "ManageDocuments") ==
AuthAccessLevel.Full && i.DOCUMENT_TYPE_ID != (int) DocumentType.FlashNotes ||
i.DOCUMENT_TYPE_ID != (int)DocumentType.CallMeetingNotes ||
i.DOCUMENT_TYPE_ID != (int)DocumentType.OtherNotes ||
i.DOCUMENT_TYPE_ID != (int)DocumentType.TearSheet
? true
: false;
If I've understood this correctly one of the i.DOCUMENT_TYPE_ID consditions must equate to true? Add parenthesis to equate that first.
doc.canView = IoC.Resolve<IClientAuthorizationService>().Authorize("Put", "ManageDocuments") ==
AuthAccessLevel.Full && (i.DOCUMENT_TYPE_ID == (int) DocumentType.FlashNotes ||
i.DOCUMENT_TYPE_ID == (int)DocumentType.CallMeetingNotes ||
i.DOCUMENT_TYPE_ID == (int)DocumentType.OtherNotes ||
i.DOCUMENT_TYPE_ID == (int)DocumentType.TearSheet)
Also there's no need for the true or false as it's already a bool.
I think what you're trying to do can be simplified into something like this:
var rejectedTypes = new[] { DocumentType.FlashNotes, DocumentType.CallMeetingNotes,
DocumentType.OtherNotes, DocumentType.TearSheet }.Cast<int>();
var accessLevel = IoC.Resolve<IClientAuthorizationService>()
.Authorize("Put", "ManageDocuments");
doc.canView = ((accessLevel == AuthAccessLevel.Full) &&
!rejectedTypes.Contains(i.DOCUMENT_TYPE_ID));
I think there's a mistake in the logic here. Try:
doc.canView = IoC.Resolve<IClientAuthorizationService>().Authorize("Put", "ManageDocuments") ==
AuthAccessLevel.Full && !(i.DOCUMENT_TYPE_ID == (int) DocumentType.FlashNotes ||
i.DOCUMENT_TYPE_ID == (int)DocumentType.CallMeetingNotes ||
i.DOCUMENT_TYPE_ID == (int)DocumentType.OtherNotes ||
i.DOCUMENT_TYPE_ID == (int)DocumentType.TearSheet);
It's an order of operations problem. You can find out more about ordering it here:
doc.canView = IoC.Resolve<IClientAuthorizationService>().Authorize("Put", "ManageDocuments") ==
AuthAccessLevel.Full && (i.DOCUMENT_TYPE_ID != (int) DocumentType.FlashNotes &&
i.DOCUMENT_TYPE_ID != (int)DocumentType.CallMeetingNotes &&
i.DOCUMENT_TYPE_ID != (int)DocumentType.OtherNotes &&
i.DOCUMENT_TYPE_ID != (int)DocumentType.TearSheet)
? true // Redundant code but included to show ternary operator
: false;
I have this
from d in db.v_Report_CompanySearches
orderby d.InquiryLogID descending
where (mPersonName == null || d.AccountName.ToLower() == mPersonName || d.PersonName.ToLower() == mPersonName) &&
(mCompanyName == null || TagsContain(d.CompanySearchTerm, mCompanyName)) &&
d.CreateDT >= mFrom && d.CreateDT <= mTo
select (d);
and
private bool TagsContain(string terms, string val)
{
string[] tags = terms.ToLower().Split(';');
return tags.Contains(val.ToLower());
}
but it crashes with not supported error. I think it's because I'm using a custom function TagsContain. How can I do that function in linq without custom stuff?
Thanks
Id TagsContain isn't supported by EF and have an underlying SQL function, it will crash. That's exactly what is happening here.
This however, should work:
from d in db.v_Report_CompanySearches
orderby d.InquiryLogID descending
where (mPersonName == null || d.AccountName.ToLower() == mPersonName || d.PersonName.ToLower() == mPersonName) &&
(mCompanyName == null || d.CompanySearchTerm.Contains(mCompanyName)) &&
d.CreateDT >= mFrom && d.CreateDT <= mTo
select (d);
Provider not able convert your custom function the sql. And I afraid split is one of the functions which not supported for generating sql.
You can use it without .Split
var query =
db.v_Report_CompanySearches
.Where(report => report.CreateDT >= from)
.Where(report => report.CreateDT <= to);
if (String.IsNullOrEmpty(personName) == false)
{
query = query.Where(report => report.AccountName.ToLower() == personName ||
report.PersonName.ToLower() == personName);
}
if (String.IsNullOrEmpty(companyName) == false)
{
query = query.Where(report => report.CompanySearchTerm.StartsWith($"{companyName};") ||
report.CompanySearchTerm.Contains($";{companyName};")) ||
report.CompanySearchTerm.EndsWith($";{companyName}"))
}
var result = query.OrderByDescending(report => report.InquiryLogID).ToList();
What Fabio said is right. Split function of c# can not be converted into SQL query. So, you have one way here
Get all the values from DB into C# List object and then apply the split filter over it.
var myListObject = (from d in db.v_Report_CompanySearches
orderby d.InquiryLogID descending
where (mPersonName == null || d.AccountName.ToLower() == mPersonName || d.PersonName.ToLower() == mPersonName) &&
d.CreateDT >= mFrom && d.CreateDT <= mTo
select (d)).ToList();
Then
var afterFilterObject = myListObject.Where(d => (d.mCompanyName == null || TagsContain(d.CompanySearchTerm, mCompanyName))).ToList();
Method to be called
private bool TagsContain(string terms, string val)
{
string[] tags = terms.ToLower().Split(';');
return tags.Contains(val.ToLower());
}
I'm trying to write a linq query that uses an if statement.
In the code below I'm searching for matches of
n.SAU_ID = sau.SAUID where
ReportingPeriod column contains "Oct1" then
FiscalYear - aprYearDiff = sau.SAUYearCode.
Else
FiscalYear - octYearDiff = sau.SAUYearCode.
My code is only giving matches for the SAUID and "Oct1".
What code is needed to implement theese statements?
int FiscalYear = 2014;
List<String> addtowns = new List<string>();
List<Stage_Reorg> reorg = _entities.Stage_Reorg.ToList();
int aprYearDiff = 2;
int octYearDiff = 1;
foreach (var sau in reorg)
{
addtowns.AddRange(_entities.Stage_EPSSubsidySADCSDTown
.Where(n => n.SAU_ID == sau.SAUID
&& (n.ReportingPeriod == "Oct1"
? (FiscalYear - aprYearDiff) == sau.SAUYearCode
: (FiscalYear - octYearDiff) == sau.SAUYearCode))
.Select(n => n.TownCode ));
}
This is a bad idea anyway. Transform the condition to
(n.ReportingPeriod == "Oct1" && (FiscalYear - aprYearDiff) == sau.SAUYearCode)
|| (n.ReportingPeriod != "Oct1" && (FiscalYear - octYearDiff) == sau.SAUYearCode)
Here is a possible way but this probably won't work with EF. You will need to load all records into memory then perform the filtering:
addtowns.AddRange(_entities.Stage_EPSSubsidySADCSDTown
.Where(n => {
bool b = n.ReportingPeriod == "Oct1"
? (FiscalYear - aprYearDiff) == sau.SAUYearCode
: (FiscalYear - octYearDiff) == sau.SAUYearCode);
return b && n.SAU_ID == sau.SAUID;
}).Select(n => n.TownCode ))
How Can I use Condition in Where Clause?
user can select section,product and model from list and see the result.
i add an item See All in all the filed,if user select See All,he can see all product in all section.so i want to write
a query that check for value if every property equal -1 dot bring in where condition.
//My Model
struct Model
{
public int SectionCode{get;set;}
public int ProductCode{get;set;}
public int ModelCode{get;set;}
}
var query=DBContext.Model.Where(data=>data.ModelCode==_ModelCode//if ModelCode!=-1
&& ProductCode==_ProductCode//if ProductCode!=-1
&& SectionCode==_SectionCode//if SectionCode!=-1 )
I know that i can write it with some if but i have to check a lot of condition.so i want to know, how can i write if in where Clause?
Just don't add a where clause if you don't need it, i.e:
IQueryable<Model> query = DBContext.Model;
if(_ModelCode != -1)
{
query = query.Where(data=>data.ModelCode==_ModelCode);
}
if(_ProductCode!= -1)
{
query = query.Where(data=>data.ProductCode==_ProductCode);
}
if(_SectionCode!= -1)
{
query = query.Where(data=>data.SectionCode==_SectionCode);
}
Try this :
var query=DBContext.Model.Where(data => (ModelCode == -1 || data.ModelCode == _ModelCode)
&& (ProductCode == -1 || ProductCode == _ProductCode)
&& (SectionCode == -1 || SectionCode == _SectionCode)
You could achieve this using logical operators:
var query = DBContext.Model.Where(data =>
(_ModelCode == -1 || data.ModelCode == _ModelCode)
&& (_ProductCode == -1 || data.ProductCode == _ProductCode)
&& (_SectionCode == -1 || data.SectionCode == _SectionCode))
A User in my system can have Email, Mobile or Phone and based on the values passed I am checking some conditions and then setting the ContactDataStatus (which is an enum) for each. I am then checking the ContactDataStatus to determine whether the provided contact details were valid.
The enum has the following definition
public enum ContactDataStatus
{
ExistsButUnverified = 1,
ExisitsAndVerified = 2,
IsValid = 3,
IsUninitialized = 4
}
I wrote the following if conditions to set isValid variable
isValid = false;
if (emailStatus == ContactDataStatus.IsValid &&
(mobileStatus == ContactDataStatus.IsValid ||
mobileStatus == ContactDataStatus.IsUninitialized)
&& (phoneStatus == ContactDataStatus.IsValid ||
phoneStatus == ContactDataStatus.IsUninitialized))
{
isValid = true;
}
else if (mobileStatus == ContactDataStatus.IsValid &&
(emailStatus == ContactDataStatus.IsValid ||
emailStatus == ContactDataStatus.IsUninitialized) &&
(phoneStatus == ContactDataStatus.IsValid ||
phoneStatus == ContactDataStatus.IsUninitialized))
{
isValid = true;
}
else if (phoneStatus == ContactDataStatus.IsValid &&
(emailStatus == ContactDataStatus.IsValid ||
emailStatus == ContactDataStatus.IsUninitialized) &&
(mobileStatus == ContactDataStatus.IsValid ||
mobileStatus == ContactDataStatus.IsUninitialized))
{
isValid = true;
}
Is there a simpler/shorter way of writing this?
It would help if you told us what the values were for the enum. It sounds like you want at least one of the values to be valid, and all of the values to either be uninitialized or valid. So one way of expressing that would be:
var statuses = new[] { emailStatus, mobileStatus, phoneStatus };
bool valid = statuses.Any(x => x == ContactDataStatus.IsValid) &&
statuses.All(x => x == ContactDataStatus.IsValid ||
x == ContactDataStatus.IsUninitialized);
Or if the status enum is just IsValid, IsUninitialized and (say) IsInvalid, and you knew that the values would actually be in that set, you could write:
var statuses = new[] { emailStatus, mobileStatus, phoneStatus };
bool valid = statuses.Any(x => x == ContactDataStatus.IsValid) &&
statuses.All(x => x != ContactDataStatus.IsInvalid);
Also, I'd suggest that you removed the "is" prefix from each of the enum values - it's just fluff which makes the code harder to read IMO.
var statuses = new[] { emailStatus, mobileStatus, phoneStatus };
bool isValid = statuses
.Any(s => s == ContactDataStatus.IsValid && statuses.Except(new[] { s }).All(o => o == ContactDataStatus.IsValid || o == ContactDataStatus.IsUninitialized));