What is the difference between IEnumerable<T> and IQueryable<T> in C# and when to use which?
Hello colleagues! I'm new to C# and working with Entity Framework. I constantly get confused about when to return IEnumerable and when IQueryable.
Here's a method I have in the repository:
```csharp
public IEnumerable GetProductsByCategory(int categoryId)
{
return _context.Products.Where(p => p.CategoryId == categoryId).ToList();
}
```
But another developer said it's better to use IQueryable. I rewrote it:
```csharp
public IQueryable GetProductsByCategory(int categoryId)
{
return _context.Products.Where(p => p.CategoryId == categoryId);
}
```
Now I have a service that calls this method and then filters:
```csharp
var cheapProducts = repo.GetProductsByCategory(1).Where(p => p.Price < 100).ToList();
```
In the first case (with I
No answers yet.
Log in to leave an answer
Blogs
How to Quickly Learn Python and Land Your First Job: Timelines, Tips, and Real Examples