Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
AsEnumerable() in C#
The AsEnumerable() method in C# is used to cast a specific type to its IEnumerable<T> equivalent. It is an extension method from the System.Linq namespace that helps when you need to treat a collection as a basic enumerable sequence, often to force LINQ to Objects behavior over LINQ to SQL or Entity Framework queries.
Syntax
Following is the syntax for using AsEnumerable() −
public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source)
Usage example −
var enumerable = collection.AsEnumerable();
Parameters
source − The sequence to type as
IEnumerable<T>.
Return Value
Returns the input sequence typed as IEnumerable<T>.
Using AsEnumerable() with Arrays
The most common use case is converting arrays or other collection types to their IEnumerable equivalent −
using System;
using System.Linq;
class Demo {
static void Main() {
int[] arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
var res = arr.AsEnumerable();
foreach (var ele in res) {
Console.WriteLine(ele);
}
}
}
The output of the above code is −
10 20 30 40 50
Using AsEnumerable() to Force LINQ to Objects
A key benefit of AsEnumerable() is forcing database queries to execute locally instead of on the database server −
using System;
using System.Linq;
using System.Collections.Generic;
class Student {
public int Id { get; set; }
public string Name { get; set; }
public int Score { get; set; }
}
class Program {
static void Main() {
var students = new List<Student> {
new Student { Id = 1, Name = "Alice", Score = 85 },
new Student { Id = 2, Name = "Bob", Score = 92 },
new Student { Id = 3, Name = "Carol", Score = 78 }
};
// Force LINQ to Objects behavior
var result = students.AsEnumerable()
.Where(s => s.Score > 80)
.Select(s => s.Name);
foreach (var name in result) {
Console.WriteLine(name);
}
}
}
The output of the above code is −
Alice Bob
Comparison with Other Conversion Methods
| Method | Purpose | Creates New Collection |
|---|---|---|
| AsEnumerable() | Casts to IEnumerable<T> | No |
| ToList() | Creates a new List<T> | Yes |
| ToArray() | Creates a new array | Yes |
Conclusion
The AsEnumerable() method provides a lightweight way to cast collections to IEnumerable<T> without creating new objects. It is particularly useful for forcing LINQ queries to execute locally instead of being translated to database queries, giving you more control over query execution.
