使用LINQ打印数组

时间:2016-03-04 16:10:35

标签: 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);
        }
};

4 个答案:

答案 0 :(得分:10)

这将有效:

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

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));

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

答案 1 :(得分:1)

我不想使用LINQ(函数式编程系统)来实现副作用。我宁愿将输出foreach改为类似的东西:

Console.WriteLine(string.Join(Environment.NewLine, 
    teenAgerStudents.Select(s => s.StudentName));

答案 2 :(得分:1)

试试这个:

  // There's no need in materialization, i.e. "ToArray()"
  var target = studentArray 
    .Where(student => student.Age > 12 && student.Age < 20) // teen
    .Select(student => String.Format("Id: {0} Name: {1} Age {2}", 
              student.Id, student.Name, student.Age));

  // Printing out in one line (thanks to String.Join)
  Console.Write(String.Join(Environment.NewLine, target));

答案 3 :(得分:1)

此行会将teenAgerStudents名称打印到控制台,每行一个。

Console.Write(string.Join(Environment.NewLine, studentArray.Where(s => s.Age > 12 && s.Age < 20).Select(s=>s.StudentName)));

它取代了teenAgerStudents初始化和foreach

如果您仍然想要初始化您的teenAgeStudents列表,则可以将上一行拆分为两个

//get the teenager students in form of IEnumerable<Student>.
//cast it to array with .ToArray() after .Where() if needed.
var teenAgerStudents = studentArray.Where(s => s.Age > 12 && s.Age < 20);
//print only the students' names
Console.Write(string.Join(Environment.NewLine,teenAgerStudents.Select(s=>s.StudentName)));

希望这有帮助。