I would like to know If It's possible to create a "one-line" Linq to retrieve longest string value of specific Datatable column, meaning that all column data (numbers, dates,strings...) should be converted to string and then return longest string.
What I've found is only how to obtain longest string from a List, or max length value.
This is what I tried so far (error in Length):
string maxString = dt
.AsEnumerable()
.Select(row => row[mycolumn].ToString())
.Where(s => s.OrderByDescending(st => st.Length).First());
You are looking for ArgMax
- a value such that it has max value of some kind of property. Standard Linq doesn't provide ArgMax
but you can implement it via Aggregate
(i.e. get a single value from a sequence):
string maxString = dt
.AsEnumerable()
.Select(row => row[mycolumn].ToString())
.Aggregate((s, a) => a.Length > s.Length ? a : s);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With