使用 LINQ 打印数组
本文关键字:数组 打印 LINQ 使用 | 更新日期: 2023-09-27 18:37:28
我得到了以下代码,我正在尝试打印teenAgerStudents
,而无需在 LINQ 行之后执行 foreach。是否可以在 LINQ 行中添加打印?我是否可以在 foreach 上使用另一条新的 LINQ 行进行打印?
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);
}
};
这将起作用:
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
循环。
试试这个:
// 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));
我不喜欢使用 LINQ(一种函数式编程系统)来产生副作用。我宁愿将 for each 的输出更改为类似的东西:
Console.WriteLine(string.Join(Environment.NewLine,
teenAgerStudents.Select(s => s.StudentName));
此行将打印您的青少年学生姓名到控制台,每行一个。
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)));
希望这有帮助。