List ใน C#

  1. การสร้าง List และเข้าถึงด้วย foreach
  2. การ Add และ Remove สมาชิกใน List
  3. การ search และ sort สมาชิกใน List
  4. การใช้งาน List กับ Class
Continue reading
Posted in C#

ตัวอย่างคลาส Bank

คลาส Bank แสดงตัวอย่างการตรวจสอบ Error แล้วทำการ throw แบบต่างๆ

Transaction.cs

using System;

namespace ConsoleApp1
{
    class Transaction
    {
        public decimal Amount { get; }
        public DateTime Date { get; }
        public string Notes { get; }

        public Transaction(decimal amount, DateTime date, string note)
        {
            this.Amount = amount;
            this.Date = date;
            this.Notes = note;
        }
    }
}
Continue reading
Posted in C#

ตัวอย่างคลาส Fibonacci

คำนวณค่า Fibonacci แบบไม่ recursive แต่ใช้ IEnumerable เพื่อให้เรียกใช้ด้วย foreach ได้

FibonacciGenerator.cs

using System.Collections.Generic;

namespace ConsoleApp1
{
    class FibonacciGenerator
    {
        private Dictionary<int, int> _cache = new Dictionary<int, int>();

        private int Fib(int n) => n < 2 ? n : FibValue(n - 1) + FibValue(n - 2);

        private int FibValue(int n)
        {
            if (!_cache.ContainsKey(n))
            {
                _cache.Add(n, Fib(n));
            }

            return _cache[n];
        }

        public IEnumerable<int> Generate(int n)
        {
            for (int i = 0; i < n; i++)
            {
                yield return FibValue(i);
            }
        }
    }
}
Continue reading
Posted in C#

Dictionary ใน C#

Dictionary ทำงานในลักษณะของ key, value

  1. การใช้งาน Dictionary เบื้องต้น
  2. การใช้งาน Dictionary กับ foreach
  3. ทดลองดึง value ด้วย TryGetValue
  4. ตรวจสอบว่ามี key แล้วหรือยังด้วย ContainsKey
  5. ดึงเฉพาะ value ทั้งหมดด้วย ValueCollection
  6. ดึงเฉพาะ key ทั้งหมดด้วย KeyCollection
Continue reading
Posted in C#