在 C# 中将列表转换为 IEnumerable
本教程将讨论在 C# 中将列表转换为 IEnumerable
的方法。
使用 C# 中的 as
关键字将列表转换为 IEnumerable
我们可以使用 C# 中的 as
关键字将 List
数据结构转换为 IEnumerable
数据结构。请参见以下示例。
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);
}
}
}
}
输出:
1
2
3
4
5
在上面的代码中,我们使用 C# 中的 as
关键字将整数 ilist
的 List
转换为整数 enumerable
的 IEnumerable
。
使用 C# 中的类型转换方法将列表转换为 IEnumerable
我们还可以使用类型转换方法将 List
数据类型的对象存储到 IEnumerable
数据类型的对象中,如以下代码示例所示。
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);
}
}
}
}
输出:
1
2
3
4
5
在上面的代码中,我们使用 C# 中的类型转换方法将整数 ilist
的列表转换为整数 enumerable
的 IEnumerable
。
使用 C# 中的 LINQ 方法将列表转换为 IEnumerable
LINQ 将 SQL 查询功能与 C# 中的数据结构集成在一起。我们可以使用 LINQ 的 AsEnumerable()
函数将列表转换为 C# 中的 IEnumerable
。下面的代码示例向我们展示了如何使用 C# 中的 LINQ 的 AsEnumerable()
函数将 List
数据结构转换为 IEnumerable
数据结构。
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);
}
}
}
}
输出:
1
2
3
4
5
在上面的代码中,我们使用 C# 中的 ilist.AsEnumerable()
函数将整数 ilist
的 List
转换为整数 enumerable
的 IEnumerable
。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。