Using OR condition in LINQ C#

DoIt picture DoIt · May 12, 2016 · Viewed 17k times · Source

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?

Answer

Robert McKee picture Robert McKee · May 12, 2016
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);