Find longest string in Datatable columnFind longest string from DataReader columnWhat is the difference between String and string in C#?Hidden Features of C#?LINQ query on a DataTableCase insensitive 'Contains(string)'How do I get a consistent byte representation of strings in C# without manually specifying an encoding?Group By Multiple ColumnsFind intersecting DataRows in a List of DataTablesGet the sum of a datatable columnC# LINQ is taking DataTable AsEnumerable and changing the column datatypeSearch for an integer item in a datatable with string column values

Telling my mother that I have anorexia without panicking her

Square roots and cube roots equation

Can the UK veto its own extension request?

The Planck constant for mathematicians

Why would "an mule" be used instead of "a mule"?

What did Aquinas do for recreation?

Random point on a sphere

Is a suit against a Univeristy Dorm for changing policies on a whim likely to succeed (USA)?

How seriously should I take a CBP interview where I was told I have a red flag and could only stay for 30 days?

Why do sellers care about down payments?

Relocation error, error code (127) after last updates

Is there an inconsistency about Natasha Romanoff's middle name in the MCU?

Resume: How to quantify my contributions as a software engineer?

What is this unknown executable on my boot volume? Is it Malicious?

Splice or replace

Evidence that matrix multiplication cannot be done in O(n^2 poly(log(n))) time

Were Roman public roads build by private companies?

Has SHA256 been broken by Treadwell Stanton DuPont?

Maintenance tips to prolong engine lifespan for short trips

What is my breathable atmosphere composed of?

What's the biggest organic molecule that could have a smell?

Why is Kirchoff's loop rule true in a DC circuit?

Does my opponent need to prove his creature has morph?

Could a Scotland-NI bridge break Brexit impasse?



Find longest string in Datatable column


Find longest string from DataReader columnWhat is the difference between String and string in C#?Hidden Features of C#?LINQ query on a DataTableCase insensitive 'Contains(string)'How do I get a consistent byte representation of strings in C# without manually specifying an encoding?Group By Multiple ColumnsFind intersecting DataRows in a List of DataTablesGet the sum of a datatable columnC# LINQ is taking DataTable AsEnumerable and changing the column datatypeSearch for an integer item in a datatable with string column values






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








11















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());









share|improve this question


























  • "This is what I tried so far (obviously not working)" > Not so obvious, please explain.

    – Patrick Hofman
    Apr 15 at 7:18











  • @PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"

    – Lucy82
    Apr 15 at 7:20






  • 1





    No need to use Where(). This should do the trick: .Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();

    – Stephan Bauer
    Apr 15 at 7:20











  • @StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)

    – Lucy82
    Apr 15 at 7:24











  • If you are loading that datatable from a database you should probably consider writing SQL to do this instead. Loading an entire table into memory and processing it with Linq is probably a lot slower.

    – Marie
    Apr 15 at 13:26

















11















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());









share|improve this question


























  • "This is what I tried so far (obviously not working)" > Not so obvious, please explain.

    – Patrick Hofman
    Apr 15 at 7:18











  • @PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"

    – Lucy82
    Apr 15 at 7:20






  • 1





    No need to use Where(). This should do the trick: .Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();

    – Stephan Bauer
    Apr 15 at 7:20











  • @StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)

    – Lucy82
    Apr 15 at 7:24











  • If you are loading that datatable from a database you should probably consider writing SQL to do this instead. Loading an entire table into memory and processing it with Linq is probably a lot slower.

    – Marie
    Apr 15 at 13:26













11












11








11


3






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());









share|improve this question
















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());






c# linq






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 15 at 7:38









Dmitry Bychenko

122k15 gold badges115 silver badges150 bronze badges




122k15 gold badges115 silver badges150 bronze badges










asked Apr 15 at 7:17









Lucy82Lucy82

18012 bronze badges




18012 bronze badges















  • "This is what I tried so far (obviously not working)" > Not so obvious, please explain.

    – Patrick Hofman
    Apr 15 at 7:18











  • @PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"

    – Lucy82
    Apr 15 at 7:20






  • 1





    No need to use Where(). This should do the trick: .Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();

    – Stephan Bauer
    Apr 15 at 7:20











  • @StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)

    – Lucy82
    Apr 15 at 7:24











  • If you are loading that datatable from a database you should probably consider writing SQL to do this instead. Loading an entire table into memory and processing it with Linq is probably a lot slower.

    – Marie
    Apr 15 at 13:26

















  • "This is what I tried so far (obviously not working)" > Not so obvious, please explain.

    – Patrick Hofman
    Apr 15 at 7:18











  • @PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"

    – Lucy82
    Apr 15 at 7:20






  • 1





    No need to use Where(). This should do the trick: .Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();

    – Stephan Bauer
    Apr 15 at 7:20











  • @StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)

    – Lucy82
    Apr 15 at 7:24











  • If you are loading that datatable from a database you should probably consider writing SQL to do this instead. Loading an entire table into memory and processing it with Linq is probably a lot slower.

    – Marie
    Apr 15 at 13:26
















"This is what I tried so far (obviously not working)" > Not so obvious, please explain.

– Patrick Hofman
Apr 15 at 7:18





"This is what I tried so far (obviously not working)" > Not so obvious, please explain.

– Patrick Hofman
Apr 15 at 7:18













@PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"

– Lucy82
Apr 15 at 7:20





@PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"

– Lucy82
Apr 15 at 7:20




1




1





No need to use Where(). This should do the trick: .Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();

– Stephan Bauer
Apr 15 at 7:20





No need to use Where(). This should do the trick: .Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();

– Stephan Bauer
Apr 15 at 7:20













@StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)

– Lucy82
Apr 15 at 7:24





@StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)

– Lucy82
Apr 15 at 7:24













If you are loading that datatable from a database you should probably consider writing SQL to do this instead. Loading an entire table into memory and processing it with Linq is probably a lot slower.

– Marie
Apr 15 at 13:26





If you are loading that datatable from a database you should probably consider writing SQL to do this instead. Loading an entire table into memory and processing it with Linq is probably a lot slower.

– Marie
Apr 15 at 13:26












3 Answers
3






active

oldest

votes


















10
















You are almost there:



string maxString = dt.AsEnumerable()
.Select(row => row[mycolumn].ToString())
.OrderByDescending(st => st.Length).FirstOrDefault();


A Where expects a predicate (function that will return true or false). Instead just order the projection (the .Select) as you did and retrieve the first item.




Notice that is is an O(nlogn) solution which can be improved to an O(n) solution by not sorting but by finding the item with the max length. One possible way of doing so is an in Dimitry's answer. For less than huge collections I'm not sure one would really feel the difference but it is indeed worth noticing this.




See that you can also use MoreLinq's .MaxBy that can be added through Nuget (For the GitHub repo) which will both give you the O(n) performance and the desired "one-liner":



var row = dt.AsEnumerable().MaxBy(r => r[mycolumn].ToString().Length);





share|improve this answer






















  • 3





    Isn't sorting to get the max a innefficient? Or does LINQ optimise that?

    – RoadRunner
    Apr 15 at 8:06







  • 1





    @RoadRunner - you are right that sorting will be less efficient. This is an O(nlogn) solution while one can do O(n) as in the answer below. I tried to keep as close to the original as possible

    – Gilad Green
    Apr 15 at 8:55











  • IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.

    – Marie
    Apr 15 at 13:28


















15
















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);





share|improve this answer






















  • 2





    This solution is likely much faster than the accepted answer since it doesn't have to actually sort the list, just iterate it once.

    – Marie
    Apr 15 at 13:29







  • 2





    @Marie yes, I tested, this is the fastest one. Though It differs for 1 second comparing to Gilad Green answer in my test for exporting data into Excel with OpenXML for 320k+ rows and 7 columns.

    – Lucy82
    Apr 16 at 7:27



















3
















First of all do not use AsEnumerable right after dt..
Write somehow like this:



dt.OrderByDescending(row => row[mycolumn].Length).First();





share|improve this answer

























  • AsEnumerable shouldn't be used because it transfers calculations to app memory, when my example forces it to perform calculations at sql server. When all calculations done First() transfers the result to app memory. Try my example and tell me if it works, ok?

    – NoImagination
    Apr 15 at 8:38












  • @Lucy82, well i checked my example and it works perfectly :). But as people above noticed it would be much better to find Max value by aggregation function. It requires just 1 cycle when OrderBy sorts.

    – NoImagination
    Apr 15 at 12:39












  • @Lucy82 Neither the accepted, nor Dmitry's, answer would be good for large datasets that are persisted in a database. Ie. if dt is a table in a database and contains thousands of rows the other answers would first fetch all those rows and then do the sorting to get the max value.

    – Taemyr
    Apr 15 at 12:44











  • @NoImagination I might be wrong but the question isnt tagged entity or anything. Isn't "when my example forces it to perform calculations at sql server" only true if they are using an ORM that supports that functionality?

    – Marie
    Apr 15 at 13:31











  • @NoImagination It stands to reason that "dt" stands for DataTable (the row[column] part also makes no sense at all for a EF query) which means that leaving the AsEnumerable off simply won't work. It also means that the data is already in memory so really nothing lost there.

    – Voo
    Apr 15 at 17:57














Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);














draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55684177%2ffind-longest-string-in-datatable-column%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









10
















You are almost there:



string maxString = dt.AsEnumerable()
.Select(row => row[mycolumn].ToString())
.OrderByDescending(st => st.Length).FirstOrDefault();


A Where expects a predicate (function that will return true or false). Instead just order the projection (the .Select) as you did and retrieve the first item.




Notice that is is an O(nlogn) solution which can be improved to an O(n) solution by not sorting but by finding the item with the max length. One possible way of doing so is an in Dimitry's answer. For less than huge collections I'm not sure one would really feel the difference but it is indeed worth noticing this.




See that you can also use MoreLinq's .MaxBy that can be added through Nuget (For the GitHub repo) which will both give you the O(n) performance and the desired "one-liner":



var row = dt.AsEnumerable().MaxBy(r => r[mycolumn].ToString().Length);





share|improve this answer






















  • 3





    Isn't sorting to get the max a innefficient? Or does LINQ optimise that?

    – RoadRunner
    Apr 15 at 8:06







  • 1





    @RoadRunner - you are right that sorting will be less efficient. This is an O(nlogn) solution while one can do O(n) as in the answer below. I tried to keep as close to the original as possible

    – Gilad Green
    Apr 15 at 8:55











  • IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.

    – Marie
    Apr 15 at 13:28















10
















You are almost there:



string maxString = dt.AsEnumerable()
.Select(row => row[mycolumn].ToString())
.OrderByDescending(st => st.Length).FirstOrDefault();


A Where expects a predicate (function that will return true or false). Instead just order the projection (the .Select) as you did and retrieve the first item.




Notice that is is an O(nlogn) solution which can be improved to an O(n) solution by not sorting but by finding the item with the max length. One possible way of doing so is an in Dimitry's answer. For less than huge collections I'm not sure one would really feel the difference but it is indeed worth noticing this.




See that you can also use MoreLinq's .MaxBy that can be added through Nuget (For the GitHub repo) which will both give you the O(n) performance and the desired "one-liner":



var row = dt.AsEnumerable().MaxBy(r => r[mycolumn].ToString().Length);





share|improve this answer






















  • 3





    Isn't sorting to get the max a innefficient? Or does LINQ optimise that?

    – RoadRunner
    Apr 15 at 8:06







  • 1





    @RoadRunner - you are right that sorting will be less efficient. This is an O(nlogn) solution while one can do O(n) as in the answer below. I tried to keep as close to the original as possible

    – Gilad Green
    Apr 15 at 8:55











  • IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.

    – Marie
    Apr 15 at 13:28













10














10










10









You are almost there:



string maxString = dt.AsEnumerable()
.Select(row => row[mycolumn].ToString())
.OrderByDescending(st => st.Length).FirstOrDefault();


A Where expects a predicate (function that will return true or false). Instead just order the projection (the .Select) as you did and retrieve the first item.




Notice that is is an O(nlogn) solution which can be improved to an O(n) solution by not sorting but by finding the item with the max length. One possible way of doing so is an in Dimitry's answer. For less than huge collections I'm not sure one would really feel the difference but it is indeed worth noticing this.




See that you can also use MoreLinq's .MaxBy that can be added through Nuget (For the GitHub repo) which will both give you the O(n) performance and the desired "one-liner":



var row = dt.AsEnumerable().MaxBy(r => r[mycolumn].ToString().Length);





share|improve this answer















You are almost there:



string maxString = dt.AsEnumerable()
.Select(row => row[mycolumn].ToString())
.OrderByDescending(st => st.Length).FirstOrDefault();


A Where expects a predicate (function that will return true or false). Instead just order the projection (the .Select) as you did and retrieve the first item.




Notice that is is an O(nlogn) solution which can be improved to an O(n) solution by not sorting but by finding the item with the max length. One possible way of doing so is an in Dimitry's answer. For less than huge collections I'm not sure one would really feel the difference but it is indeed worth noticing this.




See that you can also use MoreLinq's .MaxBy that can be added through Nuget (For the GitHub repo) which will both give you the O(n) performance and the desired "one-liner":



var row = dt.AsEnumerable().MaxBy(r => r[mycolumn].ToString().Length);






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 15 at 14:48

























answered Apr 15 at 7:20









Gilad GreenGilad Green

31.3k5 gold badges35 silver badges60 bronze badges




31.3k5 gold badges35 silver badges60 bronze badges










  • 3





    Isn't sorting to get the max a innefficient? Or does LINQ optimise that?

    – RoadRunner
    Apr 15 at 8:06







  • 1





    @RoadRunner - you are right that sorting will be less efficient. This is an O(nlogn) solution while one can do O(n) as in the answer below. I tried to keep as close to the original as possible

    – Gilad Green
    Apr 15 at 8:55











  • IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.

    – Marie
    Apr 15 at 13:28












  • 3





    Isn't sorting to get the max a innefficient? Or does LINQ optimise that?

    – RoadRunner
    Apr 15 at 8:06







  • 1





    @RoadRunner - you are right that sorting will be less efficient. This is an O(nlogn) solution while one can do O(n) as in the answer below. I tried to keep as close to the original as possible

    – Gilad Green
    Apr 15 at 8:55











  • IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.

    – Marie
    Apr 15 at 13:28







3




3





Isn't sorting to get the max a innefficient? Or does LINQ optimise that?

– RoadRunner
Apr 15 at 8:06






Isn't sorting to get the max a innefficient? Or does LINQ optimise that?

– RoadRunner
Apr 15 at 8:06





1




1





@RoadRunner - you are right that sorting will be less efficient. This is an O(nlogn) solution while one can do O(n) as in the answer below. I tried to keep as close to the original as possible

– Gilad Green
Apr 15 at 8:55





@RoadRunner - you are right that sorting will be less efficient. This is an O(nlogn) solution while one can do O(n) as in the answer below. I tried to keep as close to the original as possible

– Gilad Green
Apr 15 at 8:55













IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.

– Marie
Apr 15 at 13:28





IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.

– Marie
Apr 15 at 13:28













15
















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);





share|improve this answer






















  • 2





    This solution is likely much faster than the accepted answer since it doesn't have to actually sort the list, just iterate it once.

    – Marie
    Apr 15 at 13:29







  • 2





    @Marie yes, I tested, this is the fastest one. Though It differs for 1 second comparing to Gilad Green answer in my test for exporting data into Excel with OpenXML for 320k+ rows and 7 columns.

    – Lucy82
    Apr 16 at 7:27
















15
















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);





share|improve this answer






















  • 2





    This solution is likely much faster than the accepted answer since it doesn't have to actually sort the list, just iterate it once.

    – Marie
    Apr 15 at 13:29







  • 2





    @Marie yes, I tested, this is the fastest one. Though It differs for 1 second comparing to Gilad Green answer in my test for exporting data into Excel with OpenXML for 320k+ rows and 7 columns.

    – Lucy82
    Apr 16 at 7:27














15














15










15









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);





share|improve this answer















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);






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 15 at 12:36

























answered Apr 15 at 7:36









Dmitry BychenkoDmitry Bychenko

122k15 gold badges115 silver badges150 bronze badges




122k15 gold badges115 silver badges150 bronze badges










  • 2





    This solution is likely much faster than the accepted answer since it doesn't have to actually sort the list, just iterate it once.

    – Marie
    Apr 15 at 13:29







  • 2





    @Marie yes, I tested, this is the fastest one. Though It differs for 1 second comparing to Gilad Green answer in my test for exporting data into Excel with OpenXML for 320k+ rows and 7 columns.

    – Lucy82
    Apr 16 at 7:27













  • 2





    This solution is likely much faster than the accepted answer since it doesn't have to actually sort the list, just iterate it once.

    – Marie
    Apr 15 at 13:29







  • 2





    @Marie yes, I tested, this is the fastest one. Though It differs for 1 second comparing to Gilad Green answer in my test for exporting data into Excel with OpenXML for 320k+ rows and 7 columns.

    – Lucy82
    Apr 16 at 7:27








2




2





This solution is likely much faster than the accepted answer since it doesn't have to actually sort the list, just iterate it once.

– Marie
Apr 15 at 13:29






This solution is likely much faster than the accepted answer since it doesn't have to actually sort the list, just iterate it once.

– Marie
Apr 15 at 13:29





2




2





@Marie yes, I tested, this is the fastest one. Though It differs for 1 second comparing to Gilad Green answer in my test for exporting data into Excel with OpenXML for 320k+ rows and 7 columns.

– Lucy82
Apr 16 at 7:27






@Marie yes, I tested, this is the fastest one. Though It differs for 1 second comparing to Gilad Green answer in my test for exporting data into Excel with OpenXML for 320k+ rows and 7 columns.

– Lucy82
Apr 16 at 7:27












3
















First of all do not use AsEnumerable right after dt..
Write somehow like this:



dt.OrderByDescending(row => row[mycolumn].Length).First();





share|improve this answer

























  • AsEnumerable shouldn't be used because it transfers calculations to app memory, when my example forces it to perform calculations at sql server. When all calculations done First() transfers the result to app memory. Try my example and tell me if it works, ok?

    – NoImagination
    Apr 15 at 8:38












  • @Lucy82, well i checked my example and it works perfectly :). But as people above noticed it would be much better to find Max value by aggregation function. It requires just 1 cycle when OrderBy sorts.

    – NoImagination
    Apr 15 at 12:39












  • @Lucy82 Neither the accepted, nor Dmitry's, answer would be good for large datasets that are persisted in a database. Ie. if dt is a table in a database and contains thousands of rows the other answers would first fetch all those rows and then do the sorting to get the max value.

    – Taemyr
    Apr 15 at 12:44











  • @NoImagination I might be wrong but the question isnt tagged entity or anything. Isn't "when my example forces it to perform calculations at sql server" only true if they are using an ORM that supports that functionality?

    – Marie
    Apr 15 at 13:31











  • @NoImagination It stands to reason that "dt" stands for DataTable (the row[column] part also makes no sense at all for a EF query) which means that leaving the AsEnumerable off simply won't work. It also means that the data is already in memory so really nothing lost there.

    – Voo
    Apr 15 at 17:57
















3
















First of all do not use AsEnumerable right after dt..
Write somehow like this:



dt.OrderByDescending(row => row[mycolumn].Length).First();





share|improve this answer

























  • AsEnumerable shouldn't be used because it transfers calculations to app memory, when my example forces it to perform calculations at sql server. When all calculations done First() transfers the result to app memory. Try my example and tell me if it works, ok?

    – NoImagination
    Apr 15 at 8:38












  • @Lucy82, well i checked my example and it works perfectly :). But as people above noticed it would be much better to find Max value by aggregation function. It requires just 1 cycle when OrderBy sorts.

    – NoImagination
    Apr 15 at 12:39












  • @Lucy82 Neither the accepted, nor Dmitry's, answer would be good for large datasets that are persisted in a database. Ie. if dt is a table in a database and contains thousands of rows the other answers would first fetch all those rows and then do the sorting to get the max value.

    – Taemyr
    Apr 15 at 12:44











  • @NoImagination I might be wrong but the question isnt tagged entity or anything. Isn't "when my example forces it to perform calculations at sql server" only true if they are using an ORM that supports that functionality?

    – Marie
    Apr 15 at 13:31











  • @NoImagination It stands to reason that "dt" stands for DataTable (the row[column] part also makes no sense at all for a EF query) which means that leaving the AsEnumerable off simply won't work. It also means that the data is already in memory so really nothing lost there.

    – Voo
    Apr 15 at 17:57














3














3










3









First of all do not use AsEnumerable right after dt..
Write somehow like this:



dt.OrderByDescending(row => row[mycolumn].Length).First();





share|improve this answer













First of all do not use AsEnumerable right after dt..
Write somehow like this:



dt.OrderByDescending(row => row[mycolumn].Length).First();






share|improve this answer












share|improve this answer



share|improve this answer










answered Apr 15 at 8:09









NoImaginationNoImagination

1781 silver badge7 bronze badges




1781 silver badge7 bronze badges















  • AsEnumerable shouldn't be used because it transfers calculations to app memory, when my example forces it to perform calculations at sql server. When all calculations done First() transfers the result to app memory. Try my example and tell me if it works, ok?

    – NoImagination
    Apr 15 at 8:38












  • @Lucy82, well i checked my example and it works perfectly :). But as people above noticed it would be much better to find Max value by aggregation function. It requires just 1 cycle when OrderBy sorts.

    – NoImagination
    Apr 15 at 12:39












  • @Lucy82 Neither the accepted, nor Dmitry's, answer would be good for large datasets that are persisted in a database. Ie. if dt is a table in a database and contains thousands of rows the other answers would first fetch all those rows and then do the sorting to get the max value.

    – Taemyr
    Apr 15 at 12:44











  • @NoImagination I might be wrong but the question isnt tagged entity or anything. Isn't "when my example forces it to perform calculations at sql server" only true if they are using an ORM that supports that functionality?

    – Marie
    Apr 15 at 13:31











  • @NoImagination It stands to reason that "dt" stands for DataTable (the row[column] part also makes no sense at all for a EF query) which means that leaving the AsEnumerable off simply won't work. It also means that the data is already in memory so really nothing lost there.

    – Voo
    Apr 15 at 17:57


















  • AsEnumerable shouldn't be used because it transfers calculations to app memory, when my example forces it to perform calculations at sql server. When all calculations done First() transfers the result to app memory. Try my example and tell me if it works, ok?

    – NoImagination
    Apr 15 at 8:38












  • @Lucy82, well i checked my example and it works perfectly :). But as people above noticed it would be much better to find Max value by aggregation function. It requires just 1 cycle when OrderBy sorts.

    – NoImagination
    Apr 15 at 12:39












  • @Lucy82 Neither the accepted, nor Dmitry's, answer would be good for large datasets that are persisted in a database. Ie. if dt is a table in a database and contains thousands of rows the other answers would first fetch all those rows and then do the sorting to get the max value.

    – Taemyr
    Apr 15 at 12:44











  • @NoImagination I might be wrong but the question isnt tagged entity or anything. Isn't "when my example forces it to perform calculations at sql server" only true if they are using an ORM that supports that functionality?

    – Marie
    Apr 15 at 13:31











  • @NoImagination It stands to reason that "dt" stands for DataTable (the row[column] part also makes no sense at all for a EF query) which means that leaving the AsEnumerable off simply won't work. It also means that the data is already in memory so really nothing lost there.

    – Voo
    Apr 15 at 17:57

















AsEnumerable shouldn't be used because it transfers calculations to app memory, when my example forces it to perform calculations at sql server. When all calculations done First() transfers the result to app memory. Try my example and tell me if it works, ok?

– NoImagination
Apr 15 at 8:38






AsEnumerable shouldn't be used because it transfers calculations to app memory, when my example forces it to perform calculations at sql server. When all calculations done First() transfers the result to app memory. Try my example and tell me if it works, ok?

– NoImagination
Apr 15 at 8:38














@Lucy82, well i checked my example and it works perfectly :). But as people above noticed it would be much better to find Max value by aggregation function. It requires just 1 cycle when OrderBy sorts.

– NoImagination
Apr 15 at 12:39






@Lucy82, well i checked my example and it works perfectly :). But as people above noticed it would be much better to find Max value by aggregation function. It requires just 1 cycle when OrderBy sorts.

– NoImagination
Apr 15 at 12:39














@Lucy82 Neither the accepted, nor Dmitry's, answer would be good for large datasets that are persisted in a database. Ie. if dt is a table in a database and contains thousands of rows the other answers would first fetch all those rows and then do the sorting to get the max value.

– Taemyr
Apr 15 at 12:44





@Lucy82 Neither the accepted, nor Dmitry's, answer would be good for large datasets that are persisted in a database. Ie. if dt is a table in a database and contains thousands of rows the other answers would first fetch all those rows and then do the sorting to get the max value.

– Taemyr
Apr 15 at 12:44













@NoImagination I might be wrong but the question isnt tagged entity or anything. Isn't "when my example forces it to perform calculations at sql server" only true if they are using an ORM that supports that functionality?

– Marie
Apr 15 at 13:31





@NoImagination I might be wrong but the question isnt tagged entity or anything. Isn't "when my example forces it to perform calculations at sql server" only true if they are using an ORM that supports that functionality?

– Marie
Apr 15 at 13:31













@NoImagination It stands to reason that "dt" stands for DataTable (the row[column] part also makes no sense at all for a EF query) which means that leaving the AsEnumerable off simply won't work. It also means that the data is already in memory so really nothing lost there.

– Voo
Apr 15 at 17:57






@NoImagination It stands to reason that "dt" stands for DataTable (the row[column] part also makes no sense at all for a EF query) which means that leaving the AsEnumerable off simply won't work. It also means that the data is already in memory so really nothing lost there.

– Voo
Apr 15 at 17:57



















draft saved

draft discarded















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55684177%2ffind-longest-string-in-datatable-column%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Tamil (spriik) Luke uk diar | Nawigatjuun

Align equal signs while including text over equalitiesAMS align: left aligned text/math plus multicolumn alignmentMultiple alignmentsAligning equations in multiple placesNumbering and aligning an equation with multiple columnsHow to align one equation with another multline equationUsing \ in environments inside the begintabularxNumber equations and preserving alignment of equal signsHow can I align equations to the left and to the right?Double equation alignment problem within align enviromentAligned within align: Why are they right-aligned?

Where does the image of a data connector as a sharp metal spike originate from?Where does the concept of infected people turning into zombies only after death originate from?Where does the motif of a reanimated human head originate?Where did the notion that Dragons could speak originate?Where does the archetypal image of the 'Grey' alien come from?Where did the suffix '-Man' originate?Where does the notion of being injured or killed by an illusion originate?Where did the term “sophont” originate?Where does the trope of magic spells being driven by advanced technology originate from?Where did the term “the living impaired” originate?