ฉันรู้ในไวยากรณ์ Linq ปกติorderby xxx descendingง่ายมาก แต่ฉันจะทำสิ่งนี้ในการแสดงออกของแลมบ์ดาได้อย่างไร
ฉันรู้ในไวยากรณ์ Linq ปกติorderby xxx descendingง่ายมาก แต่ฉันจะทำสิ่งนี้ในการแสดงออกของแลมบ์ดาได้อย่างไร
คำตอบ:
อย่างที่ Brannon พูดมันคือOrderByDescendingและThenByDescending:
var query = from person in people
orderby person.Name descending, person.Age descending
select person.Name;
เทียบเท่ากับ:
var query = people.OrderByDescending(person => person.Name)
.ThenByDescending(person => person.Age)
.Select(person => person.Name);
ใช้งานSystem.Linq.Enumerable.OrderByDescending()หรือ
ตัวอย่างเช่น:
var items = someEnumerable.OrderByDescending();
ลองสิ่งนี้:
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);
foreach (var item in list.OrderByDescending(x => x))
{
Console.WriteLine(item);
}
ลองอีกวิธีนี้:
var qry = Employees
.OrderByDescending (s => s.EmpFName)
.ThenBy (s => s.Address)
.Select (s => s.EmpCode);
ใช้งานได้เฉพาะในสถานการณ์ที่คุณมีฟิลด์ตัวเลข แต่คุณสามารถใส่เครื่องหมายลบที่ด้านหน้าชื่อฟิลด์ดังนี้:
reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);
อย่างไรก็ตามวิธีนี้ใช้งานได้แตกต่างกันเล็กน้อยOrderByDescendingเมื่อคุณใช้งานบนint?หรือdouble?หรือdecimal?เขตข้อมูล
อะไรจะเกิดขึ้นอยู่ในOrderByDescendingnulls จะเป็นที่สิ้นสุดเทียบกับวิธีการนี้ nulls จะเป็นที่จุดเริ่มต้น ซึ่งมีประโยชน์ถ้าคุณต้องการสับเปลี่ยนโมฆะโดยไม่ต้องแยกข้อมูลออกเป็นชิ้น ๆ และต่อมาต่อกัน
LastOrDefault()มักจะไม่ทำงาน แต่Tolist()จะใช้งานได้ ไม่จำเป็นต้องใช้OrderByDescendingประโยชน์Tolist()เช่นนี้
GroupBy(p => p.Nws_ID).ToList().LastOrDefault();