尝试List.Sort()时出错;

时间:2018-06-05 22:40:55

标签: c#

我有这个方法创建并返回一个字符串列表,然后按字母顺序对字符串进行排序。我在尝试此代码时收到错误(无法将void隐式转换为System.Collections.Generic.List<string>):

public static List<string> ReturnListofFirstandLastName()
{
    List<string> names = new List<string>();

    Reademployeelist();
    for (int i =0; i < employeelist.Count;i++)
    {
        names.Add(employeelist[i].first_name + " " + employeelist[i].last_name);
    }

    return names.Sort();
}

1 个答案:

答案 0 :(得分:1)

这里的问题是Sort只会对IEnumerable进行排序,但它不会返回任何内容(与OrderBy()不同,后者返回一个新的IEnumerable

解决此问题的最简单方法是在列表中调用Sort,然后将其返回:

    // Previous code omitted

    names.Sort();
    return names;
}

作为旁注,您可能需要考虑重命名某些对象。对于初学者,属性名称通常是PascalCase(不是由下划线分隔的单词)。因此,您的员工班级不会有first_name,而是FirstName

例如:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

此外,您的employeelist只能被称为employees(通常将集合类型命名为包含类型所代表的复数形式),Reademployeelist可能更好地命名为{ {1}}(读取意味着它会读取列表,但是因为在迭代列表之前调用它,看起来它实际填充了列表)?

PopulateEmployees

并且您的方法可以命名为private static List<Employee> employees = new List<Employee>(); private static void PopulateEmployees() { employees = new List<Employee> { new Employee {FirstName = "Warren", LastName = "Buffett"}, new Employee {FirstName = "Jeff", LastName = "Bezos"}, new Employee {FirstName = "Larry", LastName = "Page"}, new Employee {FirstName = "Mark", LastName = "Zuckerberg"}, new Employee {FirstName = "Elon", LastName = "Musk"}, new Employee {FirstName = "Steve", LastName = "Jobs"}, new Employee {FirstName = "Oprah", LastName = "Winfrey"}, new Employee {FirstName = "Howard", LastName = "Schultz"}, new Employee {FirstName = "Larry", LastName = "Ellison"}, new Employee {FirstName = "Satya", LastName = "Nadella"}, }; } ,如果我们使用GetEmployeeFirstAndLastNames之类的System.Linq方法(可以选择每个员工的名字和姓氏的串联),可以稍微简化一下)和Select(它将隐式创建一个新列表,而不是我们必须这样做,我们可以返回它的结果):

OrderBy

用法示例:

public static List<string> GetEmployeeFirstAndLastNames()
{
    PopulateEmployees();

    return employees.Select(e => e.FirstName + " " + e.LastName)
        .OrderBy(name => name)
        .ToList();
}

<强>输出

enter image description here