8

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?

DoIt
  • 3,270
  • 9
  • 51
  • 103
  • var session = txns.Where(a => a.transaction_type.Equals("SALE")) .Where(a => a.transaction_type.Equals("PRE") || a.approval_status.Equals("APPROVED")) .OrderByDescending(a => a.creation_date).Select(a => a.creation_date).FirstOrDefault(); – user3953989 May 12 '16 at 19:23

2 Answers2

15
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);
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
  • How to handle `Object reference not set to an instance of an object` when one of the fields has a null value? – DoIt May 13 '16 at 18:42
  • @DoIt You can switch from using .Equals to using == which won't throw on null. I don't usually use .Equals myself, but kept it that way since the OP used it. – Robert McKee Nov 23 '22 at 17:25
3

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.

Habib
  • 219,104
  • 29
  • 407
  • 436