目前您正在尝试使用Console.WriteLine() 将序列对象listAlphabetically 直接打印到控制台。
var listAlphabetically = studentList.OrderBy(x => x.StudentName);
Console.WriteLine(listAlphabetically);
Console.WriteLine() 在内部调用对象.ToString()-方法。该对象被转换为它的string-representation,然后将打印到控制台。在您的情况下,这可能看起来像这样:System.Linq.OrderedEnumerable2[StackOverflow.Program+Student,System.String]。
要覆盖对象string-representation,您需要自己定义.ToString() 方法。因此,一个示例可能如下所示:
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
public string Country { get; set; }
public override string ToString()
{
return $"StudentID: {this.StudentID} - StudentName: {this.StudentName} - Age: {this.Age} - Country: {this.Country}";
}
}
然后您将能够迭代Students 的序列并将它们的表示打印到控制台:
var listAlphabetically = studentList.OrderBy(x => x.StudentName);
// iterate students and print them to the console
foreach (var student in listAlphabetically)
Console.WriteLine(student);
如果您只想将每个学生的单个属性打印到控制台,您可以执行以下操作:
var listAlphabetically = studentList.OrderBy(x => x.StudentName);
// iterate students and print only the ID of each student
foreach (var student in listAlphabetically)
Console.WriteLine(student.StudentID);
完整示例
using System;
using System.Collections.Generic;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
public string Country { get; set; }
public override string ToString()
{
return $"StudentID: {this.StudentID} - StudentName: {this.StudentName} - Age: {this.Age} - Country: {this.Country}";
}
}
public static void Main(string[] args)
{
List<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18, Country = "Poland" } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 22, Country = "Poland" } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18, Country = "USA" } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20, Country = "USA" } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 21, Country = "Germany" }
};
var listAlphabetically = studentList.OrderBy(x => x.StudentName);
// iterate students and print them to the console
foreach (var student in listAlphabetically)
Console.WriteLine(student);
// keep console open
Console.ReadKey();
}
}
}
注意
不要忘记导入System.Collections.Generic 和System.Linq namespace,因为您将需要它们来执行上述代码。
using System.Collections.Generic;
using System.Linq;