Question

I have this code:

here I get list of longs from the database:

IQueryable<long> query = from t in table select t.LongId 

and here I try to get max from those IDs:

long max = query.Any() ? query.Max() : 0;

but no matter hwo much longs there are in the result of query, max is always set to 0.

Do you have any idea why?

Was it helpful?

Solution

If

long max = query.Any() ? query.Max() : 0;

returns zero, then one of following is true:

  1. Query does not return any results
  2. Max value in query results is zero

First case is possible when you modify your table between defining query and getting max value from query. Remember - query does not have any data. It's only query definition, and you will get data only when you execute query (e.g. call Any() or Max()).

Test:

List<long> table = new List<long> { 1, 2, 3 };
var query = from t in table select t; // query is not executed
table.Clear(); // modify data source before query is executed
Assert.False(query.Any()); // execute query on modified data source

OTHER TIPS

Wouldn't this be simpler?

long max = table.OrderByDescending(t => t.LongId)
                .Select(t => t.LongId)
                .FirstOrDefault() ?? 0;

The easiest way:

var maxId = table.OrderByDescending(x => x.LongId).First().LongId;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top