AC25
AC25

Reputation: 423

Get Max from column datatable or Default Value using Linq

I have a linq query that looks into a datatable column and gets the max value in that field, I am running into an error in which when the datatable has no rows the query is throwing an exception. I was wondering if I can handle this secnario by putting a DefaultIfEmpty but just dont know how to use it. This is the working linq query:

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

this gets the max value of that column, how do I handle return 0 if there are no rows in the datatable by using DefaultifEmpty if that is possible

Upvotes: 2

Views: 4794

Answers (2)

Ivan Doroshenko
Ivan Doroshenko

Reputation: 942

Try:

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

Upvotes: 1

Kris
Kris

Reputation: 241

Simple way

int max = dataTable.AsEnumerable().Any() ? dataTable.AsEnumerable().Max(x => Convert.ToInt32(x.Field<string>(Framework.SomeStringField))): 0

Upvotes: 0

Related Questions