Interface IEnumerable ใน C#
IEnumerable (Non-generic) เป็น Base Interface สำหรับ Collection ที่สามารถ Enumerate (วนลูป) ได้ มีเมธอดเดียว GetEnumerator() คืน IEnumerator
Definition
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
การทำงานกับ Foreach
Compiler แปลง foreach (var item in coll) เป็น:
IEnumerator enumerator = coll.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
var item = enumerator.Current;
// Loop Body
}
}
finally
{
(enumerator as IDisposable)?.Dispose();
}
Extension Methods (ใน System.Linq)
| Method | คำอธิบาย |
|---|---|
AsParallel() | Parallel Query (PLINQ) |
AsQueryable() | Convert to IQueryable (LINQ to SQL, EF) |
Cast<TResult>() | Cast Elements to Type (Throw if Fail) |
OfType<TResult>() | Filter Elements of Type (Skip Others) |
ตัวอย่าง: Cast และ OfType
using System;
using System.Collections;
using System.Linq;
class Program
{
static void Main()
{
// Non-generic Collection (ArrayList)
ArrayList list = new ArrayList { 1, "Hello", 2.5, 3, "World", null };
// Cast() - Throw ถ้าไม่ใช่ int
// var ints = list.Cast(); // Exception at "Hello"
// OfType() - กรองเฉพาะ int
var ints = list.OfType(); // 1, 3
Console.WriteLine("Integers: " + string.Join(", ", ints));
// OfType()
var strings = list.OfType(); // "Hello", "World"
Console.WriteLine("Strings: " + string.Join(", ", strings));
// AsParallel() - Parallel Processing
var doubled = ints.AsParallel().Select(x => x * 2);
Console.WriteLine("Doubled: " + string.Join(", ", doubled));
}
}
ผลลัพธ์
Integers: 1, 3
Strings: Hello, World
Doubled: 2, 6
IEnumerable vs IEnumerable<T>
| Feature | IEnumerable | IEnumerable<T> |
|---|---|---|
| GetEnumerator() | Returns IEnumerator (Non-generic) | Returns IEnumerator<T> |
| Current Property | object | T |
| Type Safety | No (Cast Required) | Yes |
| LINQ Support | Via Cast/OfType | Direct |
| Foreach Variable Type | object (or var) | T (Strongly Typed) |
Implement IEnumerable (Custom Iterator)
public class MyCollection : IEnumerable
{
private int[] data = { 1, 2, 3 };
public IEnumerator GetEnumerator()
{
// Iterator Block (C# 2.0+)
foreach (int item in data)
yield return item;
}
}
// ใช้งาน
foreach (int x in new MyCollection()) Console.WriteLine(x);