Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using OR condition in LINQ C#

I do write the following SQL query in LINQ c#

  SELECT max(creation_date) from TRS where approval_status='APPROVED' and transaction_type in ('Sale','PRE') 

I tried building below query on a list as follows

var session = txns.Where(a => a.transaction_type.Equals("SALE"))
                     .Where(a => a.transaction_type.Equals("PRE"))
                     .Where(a => a.approval_status.Equals("APPROVED"))
                     .OrderByDescending(a => a.creation_date).Select(a => a.creation_date).FirstOrDefault();

The above query didnt work as I wasn't sure of how to use Max and OR condition in LINQ c#

May I know a better solution?

like image 225
DoIt Avatar asked May 12 '16 19:05

DoIt


People also ask

Which clause is used for conditions in LINQ?

In LINQ, we can use Where() clause in the query to define multiple conditions, as shown below. This is how we can use LINQ where clause filtering operator to filter data based on conditions.

How do you query in LINQ?

In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).

What is using system LINQ in C#?

Linq Namespace. Provides classes and interfaces that support queries that use Language-Integrated Query (LINQ).


2 Answers

var session = txns
  .Where(a => a.transaction_type.Equals("SALE") || a.transaction_type.Equals("PRE"))
  .Where(a => a.approval_status.Equals("APPROVED"))
  .Select(a=>a.creation_date).Max();

or

var txtypes=new[]{"SALE","PRE"};
var session = txns
  .Where(a => txtypes.Contains(a.transaction_type))
  .Where(a => a.approval_status.Equals("APPROVED"))
  .Select(a=>a.creation_date).Max();

or

var session = txns
  .Where(a => a.transaction_type.Equals("SALE") || a.transaction_type.Equals("PRE"))
  .Where(a => a.approval_status.Equals("APPROVED"))
  .Max(a=>a.creation_date);
like image 184
Robert McKee Avatar answered Oct 02 '22 07:10

Robert McKee


You can use || operator to combine your two conditions or you can use Contains which would generate a query like SELECT IN (....)

var transcationTypes = new[] {"SALE", "PRE"};
var sessions = txns.Where(a => transcationTypes.Contains(a.transaction_type)
                               && a.approval_status == "APPROVED")
    .Select(a => a.creation_date)
    .Max();

Once you have filtered out the results you can use Max to select the maximum value.

like image 25
Habib Avatar answered Oct 02 '22 08:10

Habib