我有一個具有以下屬性和值的學生班。我將班級中學生的第一條記錄存盤到學生物件變數中,我如何才能將第一個學生的值存盤到串列中
List<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John"} ,
new Student() { StudentID = 2, StudentName = "Moin"} ,
new Student() { StudentID = 3, StudentName = "Bill"} ,
new Student() { StudentID = 4, StudentName = "Ram"} ,
new Student() { StudentID = 5, StudentName = "Ron"}
};
Student student = new Student();
foreach (var students in class.students)
{
student = students
break
}
List<Student> firstStudent = new List<Student>();
如何將學生的價值從班級中獲取到 firstStudent
uj5u.com熱心網友回復:
使用串列,您可以獲得第一個物件.FirstOrDefault
例如,
studentList.FirstOrDefault()
如果您使用的是 LINQ,則可以通過條件獲取此資訊,例如使用 Lambda 運算式過濾 ID;例如,
studentList.FirstOrDefault(e => e.StudentID == <value>) //replace <value> with appropriate value.
您的代碼將如下所示:
List<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John"} ,
new Student() { StudentID = 2, StudentName = "Moin"} ,
new Student() { StudentID = 3, StudentName = "Bill"} ,
new Student() { StudentID = 4, StudentName = "Ram"} ,
new Student() { StudentID = 5, StudentName = "Ron"}
};
Student student = new Student();
foreach (var students in class.students)
{
student = students
break
}
List<Student> firstStudent = studentList.FirstOrDefault();
uj5u.com熱心網友回復:
也許是這樣的。使用 linq take 從串列中獲取第一個
這是小提琴https://dotnetfiddle.net/7eU8eZ
List<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John"} ,
new Student() { StudentID = 2, StudentName = "Moin"} ,
new Student() { StudentID = 3, StudentName = "Bill"} ,
new Student() { StudentID = 4, StudentName = "Ram"} ,
new Student() { StudentID = 5, StudentName = "Ron"}
};
Class myClass = new Class(){
ClassId = 1,
Students = studentList
};
List<Student> firstStudent =
myClass.Students.OrderBy(x => x.StudentID).Take(1).ToList();
};
uj5u.com熱心網友回復:
您可以將索引與串列一起使用,它將創建一個包含一名學生的串列
List<Student> firstStudent = new List<Student> { studentList[0] };
如果你只想要第一個學生
Student firstStudent = studentList[0] ;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/483861.html
標籤:C# asp.net-mvc
上一篇:在API方法中使用[FromBody]注釋時收到404BadRequest
下一篇:顯示總專案cshtmlMVCC#
