You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#技术问题:如何从字符串列表中获取最短字符串?

获取列表中最短字符串的LINQ实现

问题里的Min()方法默认按字符串字典序比较,所以返回的是字典序最小的结果,而非长度最短的。要获取最短字符串,有几种实用的LINQ实现方式:

方法1:按长度排序后取第一个

适用于所有.NET版本,逻辑直观:

List<string> s = new List<string>{"ABCDEF","ABC", "ABCD"};
string shortestString = s.OrderBy(str => str.Length).First();

方法2:使用Aggregate手动迭代比较

不需要排序,直接遍历列表筛选最短字符串,数据量大时性能更优:

string shortestString = s.Aggregate((currentShortest, nextStr) => 
    nextStr.Length < currentShortest.Length ? nextStr : currentShortest);

方法3:.NET 6+ 专用MinBy方法(最简洁)

.NET 6及以上版本新增了MinBy方法,可直接指定排序依据为字符串长度:

string shortestString = s.MinBy(str => str.Length);

三种方法最终都会返回预期的"ABC"。

内容的提问来源于stack exchange,提问作者Sailajakowkuntla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 04:32:10