gpt4 book ai didi

c# - 使用linq列出带有必须字母的数组中的单词

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:29 25 4
gpt4 key购买 nike

我正在尝试列出字母最多的单词。我是 LINQ 的新手,有点困惑。

这是我的代码:

string sentence = "write wwww five cat com LINQ queries to do the following good abba";
string[] words = sentence.Split(' ');

IEnumerable<string> query3 = words
.Where(n => n)
.OrderBy(n.Length).Reverse;

IEnumerable<string> query33 = query3
.Where(n => n.First.length)

最佳答案

您可以直接使用OrderByDescending:

string sentence = "write wwww five cat com LINQ queries to do the following good abba";
string[] words = sentence.Split(' ');
IEnumerable<string> query3 = words
.OrderByDescending(n => n.Length);

并且您不需要第二个查询,只需要第一个 (query3)。

OrderByDescending 采用 lambda 参数来决定如何按降序对 IEnumerable 进行排序。您只需要在IEnumerable中输入字符串的Length作为排序参数即可。

更新:

(这是基于评论,而不是问题)

如果你想让所有的词都和第一个词一样长,其实你有一些选择。但是,假设您想从有序序列继续,我会使用 MaxTakeWhile:

string sentence = "write wwww five cat com LINQ queries to do the following good abba";
string[] words = sentence.Split(' ');
IEnumerable<string> query3 = words
.OrderByDescending(n => n.Length);
int max = query3.Max(n => n.Length);
var query4 = query3.TakeWhile(n => n.Length == max);

关于c# - 使用linq列出带有必须字母的数组中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com