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

วิธีใช้ OrderBy และ GroupBy ใน C# (LINQ)

OrderBy - เรียงลำดับข้อมูล

ใช้เรียงลำดับ Array/Collection แบบ Ascending (น้อยไปมาก) หรือ Descending (มากไปน้อย)

GroupBy - จัดกลุ่มข้อมูล

เป็น Operator ในกลุ่ม Grouping Operators รับ Sequence แบบแบน (Flat) มาจัดกลุ่มเป็น IGrouping<TKey, TElement> ตาม Key ที่กำหนด และคืนค่ากลุ่มของ Sequence

ตัวอย่าง GroupBy

class ElectronicGoods
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    
    public static List<ElectronicGoods> GetElectronicItems()
    {
        return new List<ElectronicGoods>()
        {
            new ElectronicGoods { Id = 1, Name = "Mobile", Category = "Phone" },
            new ElectronicGoods { Id = 2, Name = "LandLine", Category = "Phone" },
            new ElectronicGoods { Id = 3, Name = "Television", Category = "TV" },
            new ElectronicGoods { Id = 4, Name = "Grinder", Category = "Food" },
            new ElectronicGoods { Id = 5, Name = "Mixer", Category = "Food" },
        };
    }
}

class Program
{
    static void Main()
    {
        // Group by Category แล้วเรียงในกลุ่มตาม Name
        var res = ElectronicGoods.GetElectronicItems()
            .GroupBy(x => x.Category)
            .Select(x => new 
            { 
                Key = x.Key, 
                ElectronicGoods = x.OrderBy(c => c.Name) 
            });

        foreach (var group in res)
        {
            Console.WriteLine($"{group.Key} - {group.ElectronicGoods.Count()}");
            Console.WriteLine("----------");
            foreach (var item in group.ElectronicGoods)
            {
                Console.WriteLine($"{item.Name}\t{item.Category}");
            }
            Console.WriteLine();
        }
        Console.ReadKey();
    }
}

Output

Phone - 2
----------
LandLine    Phone
Mobile      Phone

TV - 1
----------
Television  TV

Food - 2
----------
Grinder     Food
Mixer       Food

ตัวอย่าง OrderBy

var res = ElectronicGoods.GetElectronicItems().OrderBy(x => x.Category);
foreach (var item in res)
{
    Console.WriteLine($"{item.Name}\t{item.Category}");
}

Output

Grinder     Food
Mixer       Food
Mobile      Phone
LandLine    Phone
Television  TV

คำสั่งเพิ่มเติม

  • OrderByDescending - เรียงจากมากไปน้อย
  • ThenBy - เรียงระดับสอง
  • GroupBy(x => x.Key, (key, items) => ...) - รูปแบบ Result Selector