TQC+ C# 認證教學手冊

302、成績查詢

LINQ 發音 link

參考程式碼

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

namespace CSD03
{
    class Program
    {
        static void Main(string[] args)
        {
            var englishScores = new[]
            {
                new { name = "Sammel", score = 98 },
                new { name = "Mary", score = 62 },
                new { name = "Jason", score = -1 },
                new { name = "Alex", score = 76 },
                new { name = "John", score = 81 },
                new { name = "Sherry", score = 34 },
                new { name = "Adam", score = 60 }
            };

            var mathScores = new[]
            {
                new { name = "Sammel", score = 77 },
                new { name = "Mary", score = 35 },
                new { name = "Jason", score = 84 },
                new { name = "Alex", score = 90 },
                new { name = "John", score = 54 },
                new { name = "Sherry", score = -1 },
                new { name = "Adam", score = -1 }
            };

            var query = from e in englishScores
                        join m in mathScores
                        on e.name equals m.name
                        where e.score >= 60 && m.score >= 60
                        select new
                        {
                            name = e.name,
                            englishScore = e.score,
                            mathScore = m.score,
                            avgScore = (e.score + m.score) / 2d
                        };

            foreach (var row in query)
            {
                Console.WriteLine("名字:{0},數學分數:{1},英文分數:{2},平均:{3:0.00}",
                    row.name,
                    row.mathScore,
                    row.englishScore,
                    row.avgScore
                );
            }

            Console.ReadLine();
        }
    }
}