【问题标题】:List sorting compile error列表排序编译错误
【发布时间】:2013-06-07 11:54:11
【问题描述】:

我正在尝试获取一个唯一的、按字母顺序排列的行业名称(字符串)列表。这是我的代码:

HashSet<string> industryHash = new HashSet<string>();
List<string> industryList = new List<string>();
List<string> orderedIndustries = new List<string>();

// add a few items to industryHash

industryList = industryHash.ToList<string>();
orderedIndustries = industryList.Sort(); //throws compilation error

最后一行抛出编译错误: "不能将类型 'void' 隐式转换为 'System.Collections.Generic.List"

我做错了什么?

【问题讨论】:

标签: c# list sorting asp.net-3.5 hashset


【解决方案1】:

Sort 是一个 void 方法,您无法从该方法中检索值。可以关注this article

您可以使用OrderBy() 订购您的清单

【讨论】:

  • 你引用的文章是法文的。
【解决方案2】:

一种选择是使用 LINQ 并删除 industryList

HashSet<string> industryHash = new HashSet<string>();
//List<string> industryList = new List<string>();
List<string> orderedIndustries = new List<string>();

orderedIndustries = (from s in industryHash
                     orderby s
                     select s).ToList();

【讨论】:

    【解决方案3】:

    这样做:

    HashSet<string> industryHash = new HashSet<string>();
    List<string> industryList = new List<string>();
    
    // add a few items to industryHash
    
    industryList = industryHash.ToList<string>();
    List<string> orderedIndustries = new List<string>(industryList.Sort()); 
    

    注意:不要保留未排序的列表,因此仅执行行业列表.Sort() 没有真正意义

    【讨论】:

    • 不,我不知道。我只是没有意识到我可以在不复制的情况下对列表进行排序。
    • 好了,一切准备就绪^^
    【解决方案4】:

    List.Sort 对原始列表进行排序并且不返回新列表。所以要么使用这种方法,要么使用Enumerable.OrderBy + ToList

    高效:

    industryList.Sort();
    

    效率较低:

    industryList = industryList.OrderBy(s => s).ToList();
    

    【讨论】:

      【解决方案5】:

      它对列表进行就地排序。如果你想要一份副本,请使用OrderBy

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-02
        相关资源
        最近更新 更多