How can I conditionally apply a Linq operator?
if you want to only filter if certain criteria is passed, do something like this
var logs = from log in context.Logs
select log;
if (filterBySeverity)
logs = logs.Where(p => p.Severity == severity);
if (filterByUser)
logs = logs.Where(p => p.User == user);
Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less.
Linq: adding conditions to the where clause conditionally
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.
Conditional Where clause in LINQ
Try this:-
First select the data:-
var r = from t in TblFamilie
select new
{
t.ID,
t.ParentID,
t.Name,
t.CurDate
};
Then you can filter based on condition:-
if (sName!="")
r = r.Where(x => x.Name == sName);
how to put conditional WHERE clause within LINQ query
Just move the condition into the lambda:
var g = mast.Where(w => (condition
? (w.Prop1.ToLower() != "default" || w.Prop2.ToLower() != "data")
: true)
).ToList();
Linq to Entities conditional WHERE
You can use ||
operator in the query so if first condition is true, the second will not be evaluated and if first is false that is not equal to 0 second will be evaluated:
where lUserId ==0 || (a.PMId == lUserId || a.TLId == lInUserId)
Nested conditional operator in a LINQ query
You can chain many ?:
as follows:
var radData = (from stop in dbContext.stop_details
join del in dbContext.stop_event on stop.id equals del.stop_id into Inners
from sd in Inners.DefaultIfEmpty()
where stop.ship_date == startDate &&
stop.cust_ref_5_terminalID == "HEND"
let value = ((int?)sd.ontime_performance)
select new
{
shipDate = stop.ship_date,
custRef = stop.cust_ref_5_terminalID,
name = stop.customer.customer_name,
ontime = (int?)sd.ontime_performance,
OTP = value == null ? "Open" :
value < 1 ? "On time" :
value == 1 ? "One Day Late" :
value == 2 ? "Two Days Late" : "Three or more days late"
}).ToList();
Also you can store the field in a variable so you don't need to cast it each time: let value = ((int?)sd.ontime_performance)
BTW - the field being int?
you can change the value < 1
to value == 0
. Consistent with the other conditions and less confusing
C# how to use ternary conditional inside LINQ Select
It sounds like this should work for you
.Select(x => {
if (x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK) is Parameter _param)
return _param.AsString();
return x.Name;
})
Replacing conditional operator in the linq select with dynamic property
I would suggest to use LINQKit. It needs just configuring DbContextOptions
:
builder
.UseSqlServer(connectionString)
.WithExpressionExpanding(); // enabling LINQKit extension
Define helper class:
public static class LanguageExtensions
{
public static Expression<Func<T, string>> NameGetter<T>(string language)
{
var param = Expression.Parameter(typeof(T), "e");
// simple realization
var propName = "Name_" + language;
var body = Expression.PropertyOrField(param, propName);
return Expression.Lambda<Func<T, string>>(body, param);
}
}
Then you can use helper in the following way:
public List<ClientDto> GetClients(string locale)
{
var q = from c in _dbContext.Clients
select new ClientDto
{
Id = c.Id,
Name = LanguageExtensions.NameGetter<Client>(language).Invoke(e)
};
return q.ToList()
}
Related Topics
How to Seed a Random Class to Avoid Getting Duplicate Random Values
Win32 API Function to Programmatically Enable/Disable Device
Using Stringwriter for Xml Serialization
What Does the '=>' Syntax in C# Mean
Cursor.Current VS. This.Cursor
Random Number Generator with No Duplicates
C# Object Pooling Pattern Implementation
How to Download HTML Source in C#
How to Check for Permissions to Write to a Directory or File
Correct Way to Override Equals() and Gethashcode()
How to Round to the Nearest 0.5
Opensubkey() Returns Null for a Registry Key That I Can See in Regedit.Exe
How to Set Session Timeout in Web.Config
Prevent .Net Garbage Collection for Short Period of Time
Find Size of Object Instance in Bytes in C#
Get All Derived Types of a Type