在数据表列中找到最长的字符串 [英] Find longest string in Datatable column

查看:121
本文介绍了在数据表列中找到最长的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能创建单行" Linq来检索特定Datatable列的最长字符串值,这意味着所有列数据(数字,日期,字符串...)都应转换为字符串然后返回最长的字符串.

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

推荐答案

您快到了:

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

A Where需要一个谓词(该函数将返回true或false).取而代之的是像您一样对投影(.Select)进行排序并检索第一项.

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.

请注意,这是一个O(nlogn)解决方案,可以通过不进行排序而是找到具有最大长度的项目来将其改进为O(n)解决方案.这样做的一种可能方法是Dimitry的回答.对于不确定的收藏,我不确定是否真的会感到与众不同,但确实值得一提.

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.

请参见您还可以使用 MoreLinq的.MaxBy 可以通过Nuget添加(对于 GitHub存储库),它们都将为您提供O(n)性能和所需的单线":

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

这篇关于在数据表列中找到最长的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆