Max or Default

Max or Default?

Since DefaultIfEmpty isn't implemented in LINQ to SQL, I did a search on the error it returned and found a fascinating article that deals with null sets in aggregate functions. To summarize what I found, you can get around this limitation by casting to a nullable within your select. My VB is a little rusty, but I think it'd go something like this:

Dim x = (From y In context.MyTable _
Where y.MyField = value _
Select CType(y.MyCounter, Integer?)).Max

Or in C#:

var x = (from y in context.MyTable
where y.MyField == value
select (int?)y.MyCounter).Max();

How to make LINQ's Max-function return the default value if the sequence is empty?

Try this:

var myList = new List<int>();
var max = myList.DefaultIfEmpty().Max();
Console.Write(max);

LINQ's DefaultIfEmpty-method checks if the sequence is empty. If that is the case, it will return a singleton sequence: A sequence containing exactly one element. This one element has the default value of the sequence's type. If the sequence does contain elements, the DefaultIfEmpty-method will simply return the sequence itself.

See the MSDN for further information

  • on the Enumerable.DefaultIfEmpty<TSource> method and
  • the default keyword in generic code.

C# Max or default?

I'd just use DefaultIfEmpty:

int maxLength = l.Select(s => s.Length).DefaultIfEmpty().Max();

Or to specify a default:

int maxLength = l.Select(s => s.Length).DefaultIfEmpty(-1).Max();

Or use a nullable value so you can tell the different:

int? maxLength = l.Select(s => (int?) s.Length).Max();

Then maxLength will be null if l is empty.

A safe max() function for empty lists

In Python 3.4+, you can use default keyword argument:

>>> max([], default=99)
99

In lower version, you can use or:

>>> max([] or [99])
99

NOTE: The second approach does not work for all iterables. especially for iterator that yield nothing but considered truth value.

>>> max(iter([]) or 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

select max value of a column in table with no rows

SELECT COALESCE(MAX(ROUTE_ID),0) ...

Max return value if empty query

int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
.Select(x => x.ShoeSize)
.DefaultIfEmpty(0)
.Max();

The zero in DefaultIfEmpty is not necessary.

Linq Max with Default Value

Below is what I came up with. Let me know if there is a better way.

LastLogin = (from ul in db.UserLogEntities
where ul.UserID == u.UserID &&
ul.Action == "Logon" &&
ul.ActionTag == "Success"
select ul.LogDate).DefaultIfEmpty(DateTime.Now).Max()

Entity Framework calling MAX on null on Records

Yes, casting to Nullable of T is the recommended way to deal with the problem in LINQ to Entities queries. Having a MaxOrDefault() method that has the right signature sounds like an interesting idea, but you would simply need an additional version for each method that presents this issue, which wouldn't scale very well.

This is one of many mismatches between how things work in the CLR and how they actually work on a database server. The Max() method’s signature has been defined this way because the result type is expected to be exactly the same as the input type on the CLR. But on a database server the result can be null. For that reason, you need to cast the input (although depending on how you write your query it might be enough to cast the output) to a Nullable of T.

Here is a solution that looks slightly simpler than what you have above:

var version = ctx.Entries 
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Max(e =>(int?)e.Version);

Hope this helps.

SQL - SELECT with default if null

Find the maximum of floorplan. Using the isnull function, replace floorplan by its max value, whenever it is null.

  SELECT id, 
name,
price,
isnull(floorplan, (select max(floorplan) from Inventory) )
FROM Inventory
ORDER BY price

Get Max from column datatable or Default Value using Linq

Try:

Datatable.AsEnumerable()
.Select(x => Convert.ToInt32(x.Field<string>(Framework.SomeStringField)))
.DefaultIfEmpty(0)
.Max(x => x);


Related Topics



Leave a reply



Submit