【问题标题】:LINQ conversion issueLINQ 转换问题
【发布时间】:2014-03-01 22:47:39
【问题描述】:

我是 LINQ 新手,但在转换时遇到了一些问题。我必须编写一个方法来查找所有名字在姓氏之前按字母顺序排列的学生。这是我的代码:

static Student[] FindAllFirstNameBeforeSecond(Student[] students)
{
    Student[] newStudents =
        from student in students
        where student.FirstName.CompareTo(student.LastName) < 0
        select student;

    return newStudents;
}

我收到此错误:

Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<ConsoleApplication2.Student>'
to 'ConsoleApplication2.Student[]'. 
An explicit conversion exists (are you missing a cast?)

我可以得到一些关于我做错了什么的提示吗?

【问题讨论】:

    标签: c# linq type-conversion


    【解决方案1】:

    Linq 查询返回IEnumerable&lt;Student&gt; 类型的结果。您应该将其转换为数组:

    static Student[] FindAllFirstNameBeforeSecond(Student[] students)
    {
       IEnumerable<Student> newStudents =
            from student in students
            where student.FirstName.CompareTo(s.LastName) < 0
            select student;
    
        return newStudents.ToArray();
    }
    

    BTW lambda 语法在这种情况下更紧凑:

    static Student[] FindAllFirstNameBeforeSecond(Student[] students)
    {
        return students.Where(s => s.FirstName.CompareTo(student.LastName) < 0)
                       .ToArray();
    }
    

    您也可以使用s.FirstName &lt; s.LastNameArray.FindAll(如果您希望结果为数组):

    static Student[] FindAllFirstNameBeforeSecond(Student[] students)
    {
        return Array.FindAll(students, s => s.FirstName < s.LastName);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-02
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      相关资源
      最近更新 更多