[C#] การใช้ LINQ หาข้อมูลใน Multidimensional Array (2D)

สมมติว่ามี Array 2 มิติ ซึ่งมีข้อมูล ดังนี้

int[,] scores = {
    { 1, 90 },
    { 2, 78 },
    { 3, 85 },
    { 4, 92 },
    { 5, 88 }
};

จริงมัน ตัวคะแนนสอบเก็บแยกตาม Id / Score อย่างคนที่ 1 จะได้ 90 คะแนนเก่งจัง แล้วผมมีโจทย์ว่าจะหาคนที่คะแนนเกิน 85 เราเขียน Code ได้ดังนี้

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[,] scores = {
            { 1, 90 },
            { 2, 78 },
            { 3, 85 },
            { 4, 92 },
            { 5, 88 }
        };

        var highScorers = from score in scores.Cast<int>().Select((value, index) => new { value, index })
                          group score by score.index / scores.GetLength(1) into g
                          where g.ElementAt(1).value > 85
                          select new { StudentID = g.ElementAt(0).value, Score = g.ElementAt(1).value };

        foreach (var student in highScorers)
        {
            Console.WriteLine($"Student ID: {student.StudentID}, Score: {student.Score}");
        }
    }
}

หลักๆ จะเป็นการแปลง Multidimensional Array มาเป็น โครงสร้างในรูปแบบ (value, index) แล้วมา Grouping ดู Score ว่าต้องมากกว่า 85 ให้สร้าง object ใหม่ที่มี StudentID / Score

ผลลัพธ์

Student ID: 1, Score: 90
Student ID: 4, Score: 92
Student ID: 5, Score: 88

 เอาจริงๆ ทำ DTO แล้วเล่นกับข้อมูลง่ายกว่าเยอะครับ

 


Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts sent to your email.