【发布时间】:2016-06-18 11:07:39
【问题描述】:
我得到了以下代码,我试图在没有我在 LINQ 行之后创建的 foreach 的情况下打印 teenAgerStudents。
我可以在 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);
}
};
【问题讨论】:
-
是的,你可以。对于简单的情况,这很好。但是,LINQ 的性能往往比编写代码差很多。我倾向于尽可能避免它,除非我绝对确定性能不是,也永远不会成为一个因素。