Reputation: 423
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
Reputation: 942
Try:
Datatable.AsEnumerable()
.Select(x => Convert.ToInt32(x.Field<string>(Framework.SomeStringField)))
.DefaultIfEmpty(0)
.Max(x => x);
Upvotes: 1
Reputation: 241
Simple way
int max = dataTable.AsEnumerable().Any() ? dataTable.AsEnumerable().Max(x => Convert.ToInt32(x.Field<string>(Framework.SomeStringField))): 0
Upvotes: 0