1

I have a linq query by which I wanted to fetch single record on the basis of below criteria-

  1. Select column_A (int), column_B (string)
  2. Select max value row on the basis of Column_A

I tried with this query-

var result = this.context.Table1
  .Where(x => x.Id == SomeId)
  .Select(s => new { 
     s.column_A, 
     s.column_B })
  .Max(item => item.column_A); 

But I am not sure it's a valid query or not. Can somebody let me know correct way to do this. Also after this query I wanted to get those two fields value like below-

var sequence = result.column_A
var index = result.column_B
Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186
user3848036
  • 169
  • 1
  • 4
  • 14
  • 1
    `Max` will return the highest `column_A` value, not the object containing that value. – Rotem Jun 26 '18 at 14:22

1 Answers1

5

You could always do this:

var result = this.context.Table1
         .Where(x => x.Id == SomeId)
         .OrderByDescending(x=>x.columnA)
         .Select(s => new { s.column_A, s.column_B })
         .FirstOrDefault();

For Min(), you can use .OrderBy instead of .OrderByDescending

Captain Kenpachi
  • 6,435
  • 6
  • 42
  • 64
  • 1
    Would this cause the whole collection to be sorted or would that be optimized away by the compiler? – Rotem Jun 26 '18 at 14:21
  • It would sort AFTER the WHERE clause was applied. – Captain Kenpachi Jun 26 '18 at 14:24
  • This type of expression will almost always be translated to a simple SELECT ... FROM [table] WHERE ... ORDER BY [something] DESC – Captain Kenpachi Jun 26 '18 at 14:26
  • In my experience Linq expressions usually follow the order of your statements as far as possible when it is transformed to SQL. So switching around the OrderBy and Where clauses would lead to inefficiency, whereas keeping them in this order would work as expected. – Captain Kenpachi Jun 26 '18 at 14:28
  • @CaptainKenpachi, so do you means instead of using Max() I should use OrderByDescending() ? – user3848036 Jun 26 '18 at 14:30
  • I wasn't referring to the `Where` statement. I mean that we only really want one item, the one with the maximum value (an O(n) operation), but we're ordering the entire (filtered by where) collection (an O(n*logn) operation). – Rotem Jun 26 '18 at 14:30
  • Well I guess you could GroupBy(x=>x.Id).Select(x=> new { x.Max(y=> y.ColumnA), s.First().column_B } ), but I'd bet good money it'd not be any faster. – Captain Kenpachi Jun 26 '18 at 14:43