使用LINQ打印数组

nir*_*989 5 c# linq

我得到了以下代码,我试图打印teenAgerStudents没有我在LINQ线后做的foreach.我可以在LINQ系列中添加打印件吗?我可以使用另一条新的LINQ线打印而不是foreach吗?

class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        Student[] studentArray = {
                new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
                new Student() { StudentID = 2, StudentName = "Steve",  Age = 21 } ,
                new Student() { StudentID = 3, StudentName = "Bill",  Age = 25 } ,
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 31 } ,
                new Student() { StudentID = 6, StudentName = "Chris",  Age = 17 } ,
                new Student() { StudentID = 7, StudentName = "Rob",Age = 19  } ,
    };
        Student[] teenAgerStudents = studentArray.Where(s => s.Age > 12 && s.Age < 20).ToArray();

        foreach (var item in teenAgerStudents)
        {
            Console.WriteLine(item.StudentName);
        }
};
Run Code Online (Sandbox Code Playgroud)

Ale*_*rck 10

这将有效:

studentArray.Where(s => s.Age > 12 && s.Age < 20)
            .ToList()
            .ForEach(s => Console.WriteLine(item.StudentName));
Run Code Online (Sandbox Code Playgroud)

Array.ForEach采用了Action<T>它没有返回值.如果以后需要该数组,则应该坚持使用旧代码.

当然你还可以ForEach在第二个声明中使用:

List<Student> teenAgerStudent = studentArray.Where(s => s.Age > 12 && s.Age < 20).ToList();
teenAgerStudent.ForEach(s => Console.WriteLine(s.StudentName));
Run Code Online (Sandbox Code Playgroud)

但这使得它的可读性降低(在我看来),所以foreach在那种情况下我会坚持一个好的旧循环.