【问题标题】:How can I sort the contents of a string list by length descending?如何按长度降序对字符串列表的内容进行排序?
【发布时间】:2020-06-28 23:53:33
【问题描述】:

我想按长度降序对短语的字符串列表进行排序,这样:

Rory Gallagher
Rod D'Ath
Gerry McAvoy
Lou Martin

最终会变成:

Rory Gallagher
Gerry McAvoy
Lou Martin
Rod D'Ath

我想先试试这个:

List<string> slPhrasesFoundInBothDocs;
. . . // populate slPhrasesFoundInBothDocs
slPhrasesFoundInBothDocs = slPhrasesFoundInBothDocs.OrderByDescending(x => x.Length);

...但最后一行无法编译,intellisense 建议我将其更改为:

slPhrasesFoundInBothDocs = (List<string>)slPhrasesFoundInBothDocs.OrderByDescending(x => x.Length);

...我做到了。它会编译,但会引发运行时异常,即“无法转换类型为 'System.Linq.OrderedEnumerable2[System.String,System.Int32]' to type 'System.Collections.Generic.List1[System.String]' 的对象。

我需要修复此代码,还是以完全不同的方式对其进行攻击?

【问题讨论】:

  • @Jawad - 和以前一样 IEnumerable as List&lt;T&gt; 返回 null 所以这不起作用。
  • yes.. IEnumerable as List&lt;T&gt; 不起作用,因为这也是将 IENumerable 转换为 List 的另一种方式......你不能这样做。您必须通过 .ToList() 方法将 IEnumerable 转换为 List。 (只是发布我删除的原始评论)

标签: c# sorting tstringlist


【解决方案1】:

使用这个:

slPhrasesFoundInBothDocs =
    slPhrasesFoundInBothDocs
        .OrderByDescending(x => x.Length)
        .ToList();

【讨论】:

  • 我在开始格式化您的代码时取出了var。这显然是一个错字。
【解决方案2】:

List&lt;T&gt;类的定义是:

public class List<T> :  IEnumerable<T>,...

List&lt;T&gt; 类继承自 IEnumerable&lt;T&gt;OrderByDescending 返回一个 IOrderedEnumerable&lt;out TElement&gt;——它也继承自 IEnumerable&lt;T&gt;

IOrderedEnumerable接口的定义是:

public interface IOrderedEnumerable<out TElement> : IEnumerable<TElement>, IEnumerable

检查一下:

IEnumerable<string> enumerable1 = new List<string>{ "x","y"};
List<string> list1 = (List<string>)enumerable1; //valid

IEnumerable<string> enumerable2 =new  Collection<string>{ "x","y"};
List<string> list2 = (List<string>)enumerable2; //runtime error

每个List&lt;T&gt;Collection&lt;T&gt; 都是IEnumerable&lt;T&gt;,这始终是正确的。但是说每个IEnumerable&lt;T&gt; 都是List&lt;T&gt;

不会有IOrderedEnumerable&lt;out TElement&gt; 可以转换为List 的情况,因为它们不在同一个层次结构中。

所以,正如@cee sharper 提到的,我们必须调用ToList() 扩展方法,将IOrderedEnumerable&lt;out TElement&gt; 转换为List&lt;T&gt;

List<string> list = new List{"x","xx","xxx"}.OrderByDescending(x => x.Length).ToList();

【讨论】:

  • 仅供参考:当您将 List&lt;T&gt; 放在您的响应中没有反引号时,Stack Overflow 的降价解释器假定泛型表示 HTML,因为例如 &lt;T&gt; 不是一个有效的 HTML 元素,它会删除它。我已编辑您的回复,在类型引用周围添加反引号以缓解这种情况。
猜你喜欢
  • 2020-09-25
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 2014-02-13
  • 2017-01-09
  • 1970-01-01
  • 2011-11-26
  • 2021-08-02
相关资源
最近更新 更多