Is It possible to create a Linq for retrieving longest string values of DataReader columns ? Column data should be converted to string and then return longest string.
What I know so far is how to get same thing with DataTable which is Enumerable (as I asked here), example:
string maxString = dt
.AsEnumerable()
.Select(row => row[mycolumn].ToString())
.OrderByDescending(st => st.Length)
.FirstOrDefault();
I've tried combining upper solution for DataReader like this:
var enumerable = reader
.Cast<IDataRecord>();
string max_string = enumerable
.Select(record => record.GetName(col).ToString())
.Aggregate((s, a) => a.Length > s.Length ? a : s);
Unfortunally this doesn't work, I get
Sequence contains no elements in at System.Linq.Enumerable.Aggregate
error. Thanks for help in advance :)
EDIT: I'm looking for a solution without loading data into Datatable etc., just directly from DataReader object. I'm trying to avoid "Out of memory exception", because data is large.
Latest attempt, suggested by Power Mouse (It returns correct value, but from column 1 only):
for (int col = 0; col < reader.FieldCount; col++)
{
string col_name = reader.GetName(col).ToString();
var enumerable = reader.Cast<IDataRecord>();
string max_string = enumerable.Where(x => enumerable.Max(y => y[col_name].ToString()
.Length) == x[col_name].ToString().Length)
.FirstOrDefault()?[col_name].ToString();
Console.WriteLine("max string of column is : " + max_string);
}