物件的排序串列給了我不想要的結果,為什么我不能按 id(整數)然后按年齡(整數)排序??串列?它僅按 Id 排序,之后使用 thenBy 時,沒有任何變化。但是,當我先使用 orderBy 名稱然后使用年齡時,它會訂購串列。
// Student collection
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 } ,
new Student() { StudentID = 6, StudentName = "Ram" , Age = 21 } ,
new Student() { StudentID = 7, StudentName = "Ram" , Age = 25 } ,
new Student() { StudentID = 8, StudentName = "Bill", Age = 19 } ,
};
var thenByResult = studentList.OrderBy(s => s.StudentName).ThenBy(s => s.StudentID).ThenByDescending(s => s.Age);
foreach (var std in thenByResult)
Console.WriteLine("Id: {0}, Name: {1}, Age:{2}",std.StudentID, std.StudentName, std.Age);
如果我按 ID 訂購,那么按年齡我會得到:

我需要的是按降序排列的年齡,在這種情況下它根本不起作用,只有當我洗掉 order 然后按學生 id 我得到年齡的降序,但我沒有得到 id 排序。
uj5u.com熱心網友回復:
如果您已經通過具有唯一 ID 的 StudentId 訂購,則不能按年齡訂購。
uj5u.com熱心網友回復:
也許您更愿意先降序Age,然后再降序StudentID?
studentList.OrderByDescending(s => s.Age).ThenBy(s => s.StudentID);
您的示例的順序studentList將更改如下:
| 原版的 | 降序排序后Age |
然后,在訂購后StudentID |
|---|---|---|
| 1 18 “約翰” 2 15 “史蒂夫” 3 25 “比爾” 4 20 “拉姆” 5 19 “羅恩” 6 21 “拉姆” 7 25 “拉姆” 8 19 “比爾” |
3 25 “比爾” 7 25 “拉姆” 6 21 “拉姆” 4 20 “拉姆” 5 19 “羅恩” 8 19 “比爾” 1 18 “約翰” 2 15 “史蒂夫” |
...studentList看起來與上一列中的相同。它所做的是在 Age內部對每個“組”進行排序;例如,根據他們的 s ( , )排序 25 歲的孩子,根據他們的s StudentID( 3, 7) 排序 19 歲的孩子。StudentID58 |
如果studentList最初未按順序排序StudentID,則結果順序可能與按降序排序后的順序不同Age。
uj5u.com熱心網友回復:
與要求不一致:
標題說“按 ID 排序,然后按年齡排序”(假設 ID 是唯一的,那么您不需要在它之后再次訂購)。
身體說你需要的是按降序排列的年齡。
代碼首先按學生姓名排序,然后按 id 排序,然后按年齡排序(假設 id 是唯一的,此時這又是無用的)。
假設您要先按年齡降序排序,然后如果有多個年齡相同的學生,他們將按 id 排序。
var thenByResult = studentList.OrderByDescending(s => s.Age).ThenBy(s => s.StudentID);
uj5u.com熱心網友回復:
您首先按StudentName欄位排序。
你的訂單是StudentName-> Id->Age
只排序Id并Age試試這個:
studentList.OrderBy(s => s.StudentID).ThenByDescending(s => s.Age);
uj5u.com熱心網友回復:
您不是按StudentID然后按Age降序排序,而是按StudentName, 然后按StudentID然后按降序排序Age。
如果您不想按 訂購StudentName,而只想按StudentID和訂購,則Age需要像這樣更改查詢:
var thenByResult = studentList.OrderBy(s => s.StudentID).ThenByDescending(s => s.Age);
uj5u.com熱心網友回復:
您應該像這樣對查詢進行排序,因為您需要 Age 降序排列,
var thenByResult = studentList.OrderBy(s => s.StudentID).ThenByDescending(s => s.Age);
這可能對你有用。
uj5u.com熱心網友回復:
你改變你的代碼
var thenByResult = studentList.OrderBy(s => s.StudentName).ThenBy(s => s.Age).ThenByDescending(s => s.Age);
到
var thenByResult = studentList.OrderBy(s => s.StudentName).ThenBy(s => s.Age).ThenByDescending(s => s.Age).ThenBy(s=>s.StudentID);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/444627.html
上一篇:LINQ用于檢查串列的所有成員是否包含在字典中的值中
下一篇:無法從內部字典/串列中檢索物件
