Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find longest string in Datatable column

Tags:

c#

linq

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());
like image 864
Lucy82 Avatar asked Apr 15 '19 07:04

Lucy82


1 Answers

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);
like image 174
Dmitry Bychenko Avatar answered Sep 22 '22 18:09

Dmitry Bychenko