Click here to Skip to main content
15,867,890 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
var deleteItems = _EFContext.DbTable.Where(so =>
  so.Identifier == ProviderIdentifier && 
  !string.IsNullOrEmpty(tranType)
    ? so.TranType.ToLower() == tranType
    : **true**);

_EFContext.DbTable.RemoveRange(deleteItems);
_EFContext.DbTable.SaveChanges();


actually tranType is something which may or may not contains value as it's optional as per dev requirement and we have to delete all matching only from DB,
like based on only identifier if trantype is null otherwise based on both(identifier and trantype condition) using linq/lambda preferably

looks like, missing something, the way i wrote lambda expression. can someone please suggest on this !

thanks

What I have tried:

able to do with if ... else.. but need to do using linq/lambda preferably as more optional conditions may need to implement in future
Posted
Updated 24-Jun-21 3:58am
v2

1 solution

Trying to push the condition to the database query will result in poor performance. Instead, only add the condition if it is required:
C#
var deleteItems = _EFContext.DbTable.Where(so => so.Identifier == ProviderIdentifier);
if (!string.IsNullOrEmpty(tranType))
{
    deleteItems = deleteItems.Where(so => so.TranType == tranType);
}

_EFContext.DbTable.RemoveRange(deleteItems);
_EFContext.SaveChanges();
 
Share this answer
 
Comments
bholey 24-Jun-21 10:15am    
thanks Richard,
actually we've 3 optional parameters may be more in future which becomes more complex and hard to handle/understand with if else so want to implement using a single linq/lambda expression statement, plz help me how to rewrite lambda expression !
Richard Deeming 24-Jun-21 10:20am    
A single lambda expression trying to combine multiple optional conditions will be much harder to understand than using if to conditionally apply the filters.
var items = source.Where(...);
if (condition1) items = items.Where(...);
if (condition2) items = items.Where(...);

vs:
var items = source.Where(x => x.Somthing && (!condition1 || x.SomethingElse) && (!condition2 || x.AnotherThing));
BillWoodruff 25-Jun-21 3:57am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900