ما الفرق بين IEnumerable<T> و IQueryable<T> في C# ومتى تستخدم كلًا منهما؟
مرحبًا أيها الزملاء! أنا مبتدئ في C# وأعمل مع Entity Framework. أخلط دائمًا بين متى يجب إرجاع IEnumerable ومتى IQueryable.
لدي طريقة في المستودع:
```csharp
public IEnumerable GetProductsByCategory(int categoryId)
{
return _context.Products.Where(p => p.CategoryId == categoryId).ToList();
}
```
لكن مطورًا آخر قال إنه من الأفضل استخدام IQueryable. أعدت كتابتها:
```csharp
public IQueryable GetProductsByCategory(int categoryId)
{
return _context.Products.Where(p => p.CategoryId == categoryId);
}
```
الآن لدي خدمة تستدعي هذه الطريقة ثم تقوم بالتصفية:
```csharp
var cheapProducts = repo.GetProductsByCategory(1).Where(p => p.Price < 100).ToList();
```
في الحالة الأولى (مع IEnumerable) كل شيء يعمل لكن ببطء. في الحالة الثانية (مع IQueryable) — أسرع، لكنني لا أفهم لماذا.
أرجو شرح الفرق الجوهري بينهما؟ متى يجب أن أستخدم IEnumerable ومتى IQueryable؟