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
Try:
Datatable.AsEnumerable()
.Select(x => Convert.ToInt32(x.Field<string>(Framework.SomeStringField)))
.DefaultIfEmpty(0)
.Max(x => x);
简单的方法
int max = dataTable.AsEnumerable().Any() ? dataTable.AsEnumerable().Max(x => Convert.ToInt32(x.Field<string>(Framework.SomeStringField))): 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.