Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Clause OrderBy ใน C# LINQ


ภาพรวม

Clause orderby ใน LINQ query syntax ใช้ จัดเรียงลำดับองค์ประกอบ ตามฟิลด์ที่ระบุ รองรับ ascending (ค่าเริ่มต้น) และ descending

ตัวอย่างโค้ดเต็ม

using System;
using System.Collections.Generic;
using System.Linq;

class Demo
{
    static void Main()
    {
        List myList = new List { "iOS by Apple", "Android by Google", "Symbian by Nokia" };
        var myLen = from element in myList
                    orderby element.Length descending
                    select element;
        Console.WriteLine("Descending order...");
        foreach (string str in myLen) Console.WriteLine(str);
    }
}

ผลลัพธ์

Descending order...
Android by Google
Symbian by Nokia
iOS by Apple

รูปแบบต่างๆ

  • orderby x - เรียงน้อยไปมาก (ascending)
  • orderby x ascending - เหมือนข้างต้น
  • orderby x descending - เรียงมากไปน้อย
  • orderby x.Length, x - เรียงหลายระดับ (primary: length, secondary: alphabetical)
  • Method syntax: list.OrderBy(x => x.Length).ThenByDescending(x => x)