How to Convert List to IEnumerable in C#
-
Convert the List to IEnumerable With the
asKeyword inC# -
Convert the List to IEnumerable With the Typecasting Method in
C# -
Convert the List to IEnumerable With the LINQ Method in
C#
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#.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedInRelated Article - Csharp List
- How to Convert an IEnumerable to a List in C#
- How to Remove Item From List in C#
- How to Join Two Lists Together in C#
- How to Get the First Object From List<Object> Using LINQ
- How to Find Duplicates in a List in C#
- The AddRange Function for List in C#
