Excluding Condition if Parameter is null
Sure it is:
public List<Pallet> GetPallet(string palletID, string locationID)
{
List<Pallet> data = new List<Pallet>();
data = data.Where(x => x.PalletID == palletID && (locationID == null || x.LocationID == locationID)).ToList();
return data;
}
LINQ WHERE statement/ignore conditions
You can add it as a condition:
var query= from x in context.a
where String.IsNullOrEmpty(param1) || (x.p == param1 && x.i == param2)
select x;
If param1
is null or empty, the condition will always be true, which effectively "ignores" the where conditions entirely.
Linq remove where if the value is null
LINQ queries can be built in multiple steps:
var result = db.APPLICATIONS
.Where(a => Statuses.Contains(a.STATUS_ID));
if (TrackingNo != null)
{
result = result.Where(a => a.TrackingNo == TrackingNo);
}
Note that if you have a Select
(a projection), you probably must build the query in multiple steps in multiple variables:
var result2 = result.Select(a => new { a.STATUS_ID });
with the result2
"built" after the if
.
Linq-to-SQL: Ignore null parameters from WHERE clause
your issue is that your are not passing in a nullable int, you are passing in a null.
try this:
Print(null);
private void Print(int? num)
{
Console.WriteLine(num.Value);
}
and you get the same error.
It should work if you do this:
var q = ( from c in db.Contacts
where
c.Active == true
&&
c.LastReviewedOn <= DateTime.Now.AddDays(-365)
&&
( // Owned by group
ownerGroupIds.Count == 0 ||
ownerGroupIds.Contains( c.OwnerGroupId.Value )
)
select c );
if(ownerUserId != null && ownerUserId.HasValue)
q = q.Where(p => p.OwnerUserId.Value == ownerUserId.Value);
return q.Count();
foreach with where and condition if parameter exists
You could put an OR condition allowing an item to pass if one of the search parameters is null or empty. Something like:
innerJoinQuery.Where(item =>
(string.IsNullOrWhiteSpace(StudentName) || item.StudentName == StudentName)
&&
(string.IsNullOrWhiteSpace(StudentSurname) || item.StudentSurname == StudentSurname)
)
Related Topics
Insert Text into the Textbox of Another Application
Asp.Net MVC Using Web API to Return a Razor View
How to Convert Style Text to C# Object Such as Class/Hashtable/Collection
.Net Class to Execute Remotely on Linux Over Ssh
How to Pass Variables from C# to JavaScript
How to Develop iOS App Using Xamarin Studio on Windows
Returning a String from Pinvoke
Read JavaScript Variable from Web Browser Control
Com Object That Has Been Separated from Its Underlying Rcw Cannot Be Used
How to Convert Image to Data Uri for HTML with C#
How to Determine The Screen Width/Height Using C#
Memcached - Using with a C# ASP.NET Application
Are P/Invoke [In, Out] Attributes Optional for Marshaling Arrays
Getters, Setters, and Properties Best Practices. Java VS. C#
Dependency Injection with a Static Logger, Static Helper Class