Find longest string in Datatable column Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!What 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
How does the particle を relate to the verb 行く in the structure「A を + B に行く」?
Is the Standard Deduction better than Itemized when both are the same amount?
Extract all GPU name, model and GPU ram
Why did the IBM 650 use bi-quinary?
How come Sam didn't become Lord of Horn Hill?
What would be the ideal power source for a cybernetic eye?
How do pianists reach extremely loud dynamics?
Output the ŋarâþ crîþ alphabet song without using (m)any letters
What is a non-alternating simple group with big order, but relatively few conjugacy classes?
Apollo command module space walk?
Can I cast Passwall to drop an enemy into a 20-foot pit?
Is it true that "carbohydrates are of no use for the basal metabolic need"?
Dating a Former Employee
Bete Noir -- no dairy
What exactly is a "Meth" in Altered Carbon?
Check which numbers satisfy the condition [A*B*C = A! + B! + C!]
English words in a non-english sci-fi novel
What does an IRS interview request entail when called in to verify expenses for a sole proprietor small business?
51k Euros annually for a family of 4 in Berlin: Is it enough?
Is it fair for a professor to grade us on the possession of past papers?
How to align text above triangle figure
ListPlot join points by nearest neighbor rather than order
Why is my conclusion inconsistent with the van't Hoff equation?
What is Wonderstone and are there any references to it pre-1982?
Find longest string in Datatable column
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!What 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 height:90px;width:728px;box-sizing:border-box;
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
add a comment |
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
"This is what I tried so far (obviously not working)" > Not so obvious, please explain.
– Patrick Hofman
yesterday
@PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"
– Lucy82
yesterday
1
No need to useWhere()
. This should do the trick:.Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();
– Stephan Bauer
yesterday
@StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)
– Lucy82
yesterday
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
yesterday
add a comment |
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
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
c# linq
edited yesterday
Dmitry Bychenko
112k1099142
112k1099142
asked yesterday
Lucy82Lucy82
1239
1239
"This is what I tried so far (obviously not working)" > Not so obvious, please explain.
– Patrick Hofman
yesterday
@PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"
– Lucy82
yesterday
1
No need to useWhere()
. This should do the trick:.Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();
– Stephan Bauer
yesterday
@StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)
– Lucy82
yesterday
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
yesterday
add a comment |
"This is what I tried so far (obviously not working)" > Not so obvious, please explain.
– Patrick Hofman
yesterday
@PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"
– Lucy82
yesterday
1
No need to useWhere()
. This should do the trick:.Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();
– Stephan Bauer
yesterday
@StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)
– Lucy82
yesterday
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
yesterday
"This is what I tried so far (obviously not working)" > Not so obvious, please explain.
– Patrick Hofman
yesterday
"This is what I tried so far (obviously not working)" > Not so obvious, please explain.
– Patrick Hofman
yesterday
@PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"
– Lucy82
yesterday
@PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"
– Lucy82
yesterday
1
1
No need to use
Where()
. This should do the trick: .Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();
– Stephan Bauer
yesterday
No need to use
Where()
. This should do the trick: .Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();
– Stephan Bauer
yesterday
@StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)
– Lucy82
yesterday
@StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)
– Lucy82
yesterday
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
yesterday
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
yesterday
add a comment |
3 Answers
3
active
oldest
votes
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);
3
Isn't sorting to get the max a innefficient? Or does LINQ optimise that?
– RoadRunner
yesterday
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
yesterday
IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.
– Marie
yesterday
add a comment |
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);
thank you too, but I allready accepted first answer. Neverthough, nice to know more solutions if one of options fails.
– Lucy82
yesterday
2
@Lucy82 This one is likely much faster since it doesnt have to actually sort the list, just iterate it once.
– Marie
yesterday
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
20 hours ago
add a comment |
First of all do not use AsEnumerable
right after dt.
.
Write somehow like this:
dt.OrderByDescending(row => row[mycolumn].Length).First();
a little explanation on this ? Accepted answer works just fine, and It uses "AsEnumerable" ?
– Lucy82
yesterday
@Lucy82, 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
yesterday
@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
yesterday
@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
yesterday
@Taemyr, exactly
– NoImagination
yesterday
|
show 8 more comments
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/3.0/"u003ecc by-sa 3.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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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);
3
Isn't sorting to get the max a innefficient? Or does LINQ optimise that?
– RoadRunner
yesterday
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
yesterday
IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.
– Marie
yesterday
add a comment |
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);
3
Isn't sorting to get the max a innefficient? Or does LINQ optimise that?
– RoadRunner
yesterday
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
yesterday
IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.
– Marie
yesterday
add a comment |
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);
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);
edited yesterday
answered yesterday
Gilad GreenGilad Green
30.8k53359
30.8k53359
3
Isn't sorting to get the max a innefficient? Or does LINQ optimise that?
– RoadRunner
yesterday
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
yesterday
IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.
– Marie
yesterday
add a comment |
3
Isn't sorting to get the max a innefficient? Or does LINQ optimise that?
– RoadRunner
yesterday
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
yesterday
IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.
– Marie
yesterday
3
3
Isn't sorting to get the max a innefficient? Or does LINQ optimise that?
– RoadRunner
yesterday
Isn't sorting to get the max a innefficient? Or does LINQ optimise that?
– RoadRunner
yesterday
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
yesterday
@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
yesterday
IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.
– Marie
yesterday
IMO you should not recommend FirstOrDefault, you should recommend a sanity check first. Then you dont have to worry about null popping up.
– Marie
yesterday
add a comment |
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);
thank you too, but I allready accepted first answer. Neverthough, nice to know more solutions if one of options fails.
– Lucy82
yesterday
2
@Lucy82 This one is likely much faster since it doesnt have to actually sort the list, just iterate it once.
– Marie
yesterday
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
20 hours ago
add a comment |
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);
thank you too, but I allready accepted first answer. Neverthough, nice to know more solutions if one of options fails.
– Lucy82
yesterday
2
@Lucy82 This one is likely much faster since it doesnt have to actually sort the list, just iterate it once.
– Marie
yesterday
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
20 hours ago
add a comment |
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);
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);
edited yesterday
answered yesterday
Dmitry BychenkoDmitry Bychenko
112k1099142
112k1099142
thank you too, but I allready accepted first answer. Neverthough, nice to know more solutions if one of options fails.
– Lucy82
yesterday
2
@Lucy82 This one is likely much faster since it doesnt have to actually sort the list, just iterate it once.
– Marie
yesterday
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
20 hours ago
add a comment |
thank you too, but I allready accepted first answer. Neverthough, nice to know more solutions if one of options fails.
– Lucy82
yesterday
2
@Lucy82 This one is likely much faster since it doesnt have to actually sort the list, just iterate it once.
– Marie
yesterday
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
20 hours ago
thank you too, but I allready accepted first answer. Neverthough, nice to know more solutions if one of options fails.
– Lucy82
yesterday
thank you too, but I allready accepted first answer. Neverthough, nice to know more solutions if one of options fails.
– Lucy82
yesterday
2
2
@Lucy82 This one is likely much faster since it doesnt have to actually sort the list, just iterate it once.
– Marie
yesterday
@Lucy82 This one is likely much faster since it doesnt have to actually sort the list, just iterate it once.
– Marie
yesterday
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
20 hours ago
@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
20 hours ago
add a comment |
First of all do not use AsEnumerable
right after dt.
.
Write somehow like this:
dt.OrderByDescending(row => row[mycolumn].Length).First();
a little explanation on this ? Accepted answer works just fine, and It uses "AsEnumerable" ?
– Lucy82
yesterday
@Lucy82, 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
yesterday
@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
yesterday
@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
yesterday
@Taemyr, exactly
– NoImagination
yesterday
|
show 8 more comments
First of all do not use AsEnumerable
right after dt.
.
Write somehow like this:
dt.OrderByDescending(row => row[mycolumn].Length).First();
a little explanation on this ? Accepted answer works just fine, and It uses "AsEnumerable" ?
– Lucy82
yesterday
@Lucy82, 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
yesterday
@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
yesterday
@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
yesterday
@Taemyr, exactly
– NoImagination
yesterday
|
show 8 more comments
First of all do not use AsEnumerable
right after dt.
.
Write somehow like this:
dt.OrderByDescending(row => row[mycolumn].Length).First();
First of all do not use AsEnumerable
right after dt.
.
Write somehow like this:
dt.OrderByDescending(row => row[mycolumn].Length).First();
answered yesterday
NoImaginationNoImagination
15317
15317
a little explanation on this ? Accepted answer works just fine, and It uses "AsEnumerable" ?
– Lucy82
yesterday
@Lucy82, 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
yesterday
@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
yesterday
@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
yesterday
@Taemyr, exactly
– NoImagination
yesterday
|
show 8 more comments
a little explanation on this ? Accepted answer works just fine, and It uses "AsEnumerable" ?
– Lucy82
yesterday
@Lucy82, 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
yesterday
@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
yesterday
@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
yesterday
@Taemyr, exactly
– NoImagination
yesterday
a little explanation on this ? Accepted answer works just fine, and It uses "AsEnumerable" ?
– Lucy82
yesterday
a little explanation on this ? Accepted answer works just fine, and It uses "AsEnumerable" ?
– Lucy82
yesterday
@Lucy82, 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
yesterday
@Lucy82, 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
yesterday
@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
yesterday
@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
yesterday
@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
yesterday
@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
yesterday
@Taemyr, exactly
– NoImagination
yesterday
@Taemyr, exactly
– NoImagination
yesterday
|
show 8 more comments
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
"This is what I tried so far (obviously not working)" > Not so obvious, please explain.
– Patrick Hofman
yesterday
@PatrickHofman, sorry, this code returns me "char does not contain a deifintion for Length"
– Lucy82
yesterday
1
No need to use
Where()
. This should do the trick:.Select(row => row[mycolumn].ToString()).OrderByDescending(st => st.Length).First();
– Stephan Bauer
yesterday
@StephanBauer, that was fast. Thanks, I knew It had to be something simple as that :)
– Lucy82
yesterday
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
yesterday