Linq query with multiple conditions - linq

how to write the linq query with these conditions..first we have to check the OrderType if this is true then and condition should be checked.How to write the query..if i close the condition at .OrderType.XYZ) then it says 'zj' doesn't belong to the current context..if we remove that no error but we r not getting the req result
bool btnvisible= datacontext.GetOrders(new List<Items> { selectedItem }).
.Where((zj => wo.OrderId== (int)BL.OrderType.PQR || zj.OrderId== (int)BL.OrderType.XYZ)
&&( zj.OrderId== (int)BL.Statuses.Assigned
|| zj.OrderId== (int)BL.Statuses.Planned
|| zj.OrderId== (int)BL.Statuses.InProgess
|| zj.OrderId== (int)BL.Statuses.Paused
|| zj.OrderId== (int)BL.Statuses.Ready)).Any();
return btnEnable;

I think this is due to some misplaced brackets. You have .Where((zj => ...) ... zj ...). The variable zj doesn't exist outside of the first set of brackets. It should be something like:
bool btnvisible= datacontext.GetOrders(new List<Items> { selectedItem })
.Where(zj => (wo.OrderId== (int)BL.OrderType.PQR || zj.OrderId== (int)BL.OrderType.XYZ)
&& (zj.OrderId== (int)BL.Statuses.Assigned
|| zj.OrderId== (int)BL.Statuses.Planned
|| zj.OrderId== (int)BL.Statuses.InProgess
|| zj.OrderId== (int)BL.Statuses.Paused
|| zj.OrderId== (int)BL.Statuses.Ready)).Any();
return btnEnable;

You appear to have a mismatched parenthesis problem.
.Where((zj => wo.OrderId== (int)BL.OrderType.PQR || zj.OrderId== (int)BL.OrderType.XYZ)
^ ^
That's mucking with the scope of your variable. Revisit it.

var readyStats = new [] {
(int)BL.Statuses.Assigned,
(int)BL.Statuses.Planned,
(int)BL.Statuses.InProgess,
(int)BL.Statuses.Paused,
(int)BL.Statuses.Ready,
};
var orderTypes = new [] {
(int)BL.OrderType.PQR,
(int)BL.OrderType.XYZ
}
bool btnvisible= datacontext.GetOrders(new List<Items> { selectedItem }).
.Where(wo => orderTypes.Contains(wo.OrderId) && readyStats.Contains(wo.OrderId)).Any();
or
bool btnvisible= datacontext.GetOrders(new List<Items> { selectedItem }).
.Any(wo => orderTypes.Contains(wo.OrderId) && readyStats.Contains(wo.OrderId));
I think the problem is here:
.Where((zj => wo.
The right version should be:
.Where(zj => zj.

Related

Ignore part of the linq query if variable equals a specific value

var longlinq = viewModel.Where(x => (x.Systems.Storage == SelectOption || x.Systems.Laptop == SelectOption ||
x.Systems._2In1 == SelectOption ||
x.Systems.Convertible == SelectOption )
||
(x.Component.Components == SelectOptionComp ||
x.Component.Boards == SelectOptionComp)
||
( x.Service.Services == SelectOptionSer ||
x.Service.DevelopmentTools_andServices == SelectOptionSer )
||
(x.Software.Softwares == SelectOptionSoft ||
x.Software.Analytics == SelectOptionSoft)
||
(x.Application.Applications == SelectOptionApp ||
x.Application.PrintImaging_andOfficeAutomation ));
Let me explain my question with an example:
For instance SelectOptionComp equals "-", then I want to ignore the parts where I used
SelectOptionComp in longlinq or set SelectOptionComp to " " in the longlinq.
I don't want to use ifs because of large number of combinations.
How do I do that?
I have used ternary operator Use the ternary operator: (SelectOptionComp == "-" ? true : (x.Component.Components == SelectOptionComp || x.Component.Boards == SelectOptionComp))

How to simplify a simple loop in Javascript?

I am now trying it out for a while and get it perfect. I am trying to simplify this for loop I created and make it actually work, without any arrays and only the most basic of basic JavaScript.
for (var x=0;x<=1;x++) {
if (secondInput == luckyNumber || secondInput == luckyNumber2 || secondInput == luckyNumber3) {
if (thirdInput == luckyNumber || thirdInput == luckyNumber2 || thirdInput == luckyNumber3) {
if (firstInput == luckyNumber || firstInput == luckyNumber2 || firstInput == luckyNumber3) {
while (firstInput !== secondInput){
while(firstInput !== thirdInput){while(secondInput !== thirdInput) {
alert('Congratulations! You got all 3 numbers correct. You\'ve won £1,000!');
}
}
}
}
}
}
Does this code make sense or am I doing something wrong? I've got the feeling that I can even leave the loop out, but it is the only way how I think it is correct.
Write a function that takes the input, compares it to the lucky numbers and returns a boolean with the result.
Call that function in your if clauses.
I don't quite understand what you are trying to do with the while loops.
You could try using this idea to help:
[1, 3, 2].sort()
(store your questions and answers in arrays, and sort both then compare. Of course, checking javascript arrays for equality is a fun new project :) )
Here you go. You said you wanted it simplified.
for (var x = 0; 1 >= x; x++) {
if (!(secondInput != luckyNumber && secondInput != luckyNumber2 && secondInput != luckyNumber3 || thirdInput != luckyNumber && thirdInput != luckyNumber2 && thirdInput != luckyNumber3 || firstInput != luckyNumber && firstInput != luckyNumber2 && firstInput != luckyNumber3)) {
while (firstInput !== secondInput) {
while (firstInput !== thirdInput) {
while (secondInput !== thirdInput) {
alert("Congratulations! You got all 3 numbers correct. You\'ve won £1,000!");
}
}
}
}
}

Dynamic field type?

I have the following code:
queryProjects = queryProjects
.Where(a => a.Field<int>("ProjectType") == projectType
&& a.Field<string>("Descr")
.IndexOf(#str, StringComparison.OrdinalIgnoreCase) >= 0
|| a.Field<string>("ProjectId")
.IndexOf(#str, StringComparison.OrdinalIgnoreCase) >= 0
|| a.Field<string>("LastChangedBy")
.IndexOf(#str, StringComparison.OrdinalIgnoreCase) >= 0
);
How can I make the a.Field< ??? > the data type dynamic where the question marks are?
On the type where your field property is, redefine it like so:
public T Field<T>(string key)
{
object field = null; // Get your field value here
return (T)field;
}

Silly question about how you format long if statements

On long if statements where they take up more than one line, do you put the conditions like AND or OR on a new line like this:
if (something
&& something else)
Or like this:
if (something &&
something else)
For complex conditions, consider extracting it into a function or a variable:
if (complexCondition(foo)) { ..
As a bonus, the name of the function or variable can be used to communicate what the condition means. This makes your code easier to read.
I typically do it the second way, since I can line up the statements. However, either way is fine when you're writing code, as long as you're consistent.
I prefer a rendition of the first. My reasoning is that deleting a condition via cut/paste/comment for any testing purposes is easier. It's a lot easier to comment out a line than it is to delete the and from the line above and comment out a line. This is more when I'm doing where clauses in SQL than in an if statement in any other given language, but is similar.
Given my druthers, I'd avoid long if tests in the first place. I'd rather do something like:
bool fTest1 = A == B ;
bool fTest2 = C ;
bool fTest3 = f(1,2,3) ;
bool fSuccess = ( fTest1 | ftest2 ) & fTest3 ;
if ( fSuccess )
...
Otherwise something like this:
if ( A == B
&& ( C == D
|| E == F
)
&& Z > Y
) {
...
}
else
{
...
}
YMMV, of course.
The former is far easier to debug, test, log, etc.
I usually format using the IDE formatter and then rearrange a bit to make it look beautiful.
I'm working in VSC and recently managed to not only write, but make readable very long conditions in nested if statements. Just use brackets and new lines like this. It should make automatic indentations:
foreach ($panstwa as $key => $value) {
if (is_object($value)) {
if (
(
($value->checkbox1 === true) && (is_string($value->panstwoZListy)) && ($value->panstwoZListy !== 'none') && ($value->panstwo === '') && ($value->panstwoZListy !== '')
) ||
(
(
($value->checkbox2 === true &&
($value->checkbox2_1 === true || $value->checkbox2_2 === true || $value->checkbox2_3 === true || $value->checkbox2_4 === true || $value->checkbox2_5 === true || $value->checkbox2_6 === true)
) ||
($value->checkbox3 === true &&
($value->checkbox3_1 === true || $value->checkbox3_2 === true)
) ||
($value->checkbox4 === true &&
(
(
($value->checkbox4_1 === true || $value->checkbox4_2 === true || $value->checkbox4_3 === true || $value->checkbox4_4 === true || $value->checkbox4_5 === true || $value->checkbox4_6 === true || $value->checkbox4_7 === true) && ($value->checkbox4_8 === false)
) ||
(
($value->checkbox4_1 === false && $value->checkbox4_2 === false && $value->checkbox4_3 === false && $value->checkbox4_4 === false && $value->checkbox4_5 === false && $value->checkbox4_6 === false && $value->checkbox4_7 === false) && ($value->checkbox4_8 === true) && (sprawdzRegexTextInput($value->prawnieUzasadnionyInteres)) && (is_object($value->dokumentacjaOceny) || is_string($value->dokumentacjaOceny))
)
)
)
) &&
(is_string($value->panstwo)) && ($value->panstwoZListy === 'none') && ($value->panstwo !== '') && (sprawdzRegexTextInput($value->panstwo)
)
) &&
((is_int($value->panstwoid) && is_numeric($value->panstwoid)) || (is_bool($value->panstwoid) && $value->panstwoid === false)) &&
(is_bool($value->zmiana))
) {
echo "ok";
//nie robię nic
} else {
$flagaPanstwa = false;
}
} else {
$flagaPanstwa = false;
}
}

using if else with LINQ Where

I want to generate dynamic query to check manage the where clause with number of parameters available...if some parameter is null i don't want to include it in the where clause
var test = from p in _db.test
where if(str1 != null){p.test == str} else i dnt wanna check p.test
I have around 14 parameters for the where clause
need help,
thanks
You can do it in steps:
// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
test = test.Where(p => p.test == str);
}
In addition to #Fredrik's answer, you can also use the short-circuit rules when evaluating boolean expressions like so:
var test = from p in _db.test
where str1 == null || p.test == str1;
Edit If you have lots of strings to test, (str1, str2, etc...) then you can use the following, which will be translated to an SQL IN clause:
var strings = new List<string>();
if (str1 != null) strings.Add(str1);
if (str2 != null) strings.Add(str2);
if (str3 != null) strings.Add(str3);
...
var test = from p in _db.test
where strings.Contains(p.test);
It's even easier if your strings are already in a collection (which, if you've got 14 of them, I assume they would be...)
Consider param1 and param2 are the parameters. Your query should be as under:
string param1 = "Value1";
string param2 = "Value2";
var q = from bal in context.FxBalanceDetails
where (string.IsNullOrEmpty(param1) || bal.Column1 == param1)
&& (string.IsNullOrEmpty(param2) || bal.Column2 == param2)
select bal;
This will ensure that the where clause gets applied for the particular parameter only when it is not null.
var test =
from p in _db.test
where p.str1 != null ? p.str1 : ""
select p;
Do you check the strings against the same Field of the entity?
If so you can write something like:
var strings = new[] { "foo", "bar", "ok", "", null };
var query = dataContext.YourTable.AsQueryable();
query = strings.Where(s => !string.IsNullOrEmpty(s))
.ToList()
.Aggregate(query, (q, s) => q.Where(e => e.YourField == s));
EDIT:
The previous solution is overcomplicated:
var strings = new[] { "foo", "bar", "ok", "", null }.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var query = dataContext.YourTable.Where(e => strings.Contains(e.YourField));

Resources