HOWTO · Csharp
How to Convert List to IEnumerable in C#
There is no need to convert a List to an IEnumerable because the List data structure already implements the IEnumerable interface but we can still use some methods to cast a List to an IEnumerable data structure.
On this page
This tutorial will discuss the methods to convert a list to IEnumerable in C#.
Convert the List to IEnumerable With the as Keyword in C#
We can convert the List data structure to the IEnumerable data structure with the as keyword in C#. See the following example.
using System;
using System.Collections.Generic;
namespace list_to_ienumerable {
class Program {
static void Main(string[] args) {
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = ilist as IEnumerable<int>;
foreach (var e in enumerable) {
Console.WriteLine(e);
}
}
}
}
Output:
1
2
3
4
5
In the above code, we converted the List of integers ilist to the IEnumerable of integers enumerable with the as keyword in C#.
Convert the List to IEnumerable With the Typecasting Method in C#
We can also use the typecasting method to store an object of the List data type into an object of the IEnumerable data type, as shown in the following code example.
using System;
using System.Collections.Generic;
namespace list_to_ienumerable {
class Program {
static void Main(string[] args) {
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = (IEnumerable<int>)ilist;
foreach (var e in enumerable) {
Console.WriteLine(e);
}
}
}
}
Output:
1
2
3
4
5
In the above code, we converted the List of integers ilist to the IEnumerable of integers enumerable with the typecasting method in C#.
Convert the List to IEnumerable With the LINQ Method in C#
The LINQ integrates the SQL query functionality with the data structures in C#. We can use the AsEnumerable() function of LINQ to convert a list to an IEnumerable in C#. The following code example shows us how we can convert a List data structure to an IEnumerable data structure with the AsEnumerable() function of LINQ in C#.
using System;
using System.Collections.Generic;
using System.Linq;
namespace list_to_ienumerable {
class Program {
static void Main(string[] args) {
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = ilist.AsEnumerable();
foreach (var e in enumerable) {
Console.WriteLine(e);
}
}
}
}
Output:
1
2
3
4
5
In the above code, we converted the List of integers ilist to the IEnumerable of integers enumerable with the ilist.AsEnumerable() function in C#.