如何在c#中将一个泛型集合转换为另一种类型的泛型集合

本文关键字:集合 泛型 一个 转换 类型 另一种 | 更新日期: 2023-09-27 18:29:18

我所在的环境包含一个RollingWindow类,其中RollingWindow<T>可以是任何类型/对象的集合。

我想创建一个C#方法来将RollingWindow<T>转换为List<T>

从本质上讲,我会以以下方式使用它:

List<int> intList = new List<int>();
List<Record> = recordList = new List<Record>();
RollingWindow<int> intWindow = new RollingWindow<int>(20); //20 elements long
RollingWindow<Record> = recordWindow = new RollingWindow<Record>(10); //10 elements long
ConvertWindowToList(intList, intWindow); // will populate intList with 20 elements in intWindow
ConvertWindowToList(intList, intWindow); // will populate recordList with 10 elements in recordWindow   

有没有想过我在c#中该怎么做?

如何在c#中将一个泛型集合转换为另一种类型的泛型集合

基于RollingWindow<T>实现IEnumerable<T>的假设;

List<int> intList = intWindow.ToList();
List<Record> recordList = recordWindow.ToList();

将工作

我假设RollingWindow<T>是从IEnumerable<T>派生的。

所以这是可能的:

var enumerableFromWin = (IEnumerable<int>) intWindow;
intList = new List<int>(enumerableFromWin);
var enumRecFromWin = (IEnumerable<Record>) recordWindow;
recordList = new List<Record>(enumRecFromWin);