动态向上转换相同类型实例的数组
dynamically upcast arrays of identically typed instances
鉴于此 linqpad 代码:
interface I {}
public class A : I {}
public class B : A {}
void Main()
{
var i = new List<I>(new I[] { new A(), new B(), new A(), new B() });
i.GroupBy(_ => _.GetType()).Select(_ => _.ToArray()).Dump();
}
将这些项转换为 IEnumerables
实际派生类型的最有效方法是什么?
我有一个带有签名的方法DoStuffToArray<T>(IEnumerable<T> items)
我需要为列表 i
中的每种不同类型动态调用一次。它是一个库方法,需要使用派生类型调用,而不是接口。
我已经用这个方法得到了两个类型数组,有没有更好的方法?
var typeGroup = i.GroupBy(_ => _.GetType()).ToArray();
var arrays = typeGroup.Select(_ => Array.CreateInstance(_.Key, _.Count())).ToArray();
for (int ai = 0; ai < typeGroup.Length; ai++)
{
var grouping = typeGroup[ai].ToArray();
int index = 0;
Array.ForEach(grouping, _ => arrays[ai].SetValue(_, index++));
}
arrays.Dump("typed arrays");
您正在寻找 OfType<T>()
.
var i = new List<I>(new I[] { new A(), new B(), new A(), new B() });
var ayes = i.OfType<A>();
var bees = i.OfType<B>();
DoStuffToArray(ayes);
DoStuffToArray(bees);
怎么样:
List<I> i = new List<I>(new I[] {new A(), new B(), new A(), new B()});
var types = i.Select(item => item.GetType()).Distinct();
foreach (var instances in types.Select(type => i.Where(item =>item.GetType() == type)))
{ DoStuffToArray(instances); }
这是我能想到的最简短的...
您将类型收集为 Disctinct
列表,然后迭代提取。但是,此方法使用大量反射,因此性能不会最佳。
鉴于此 linqpad 代码:
interface I {}
public class A : I {}
public class B : A {}
void Main()
{
var i = new List<I>(new I[] { new A(), new B(), new A(), new B() });
i.GroupBy(_ => _.GetType()).Select(_ => _.ToArray()).Dump();
}
将这些项转换为 IEnumerables
实际派生类型的最有效方法是什么?
我有一个带有签名的方法DoStuffToArray<T>(IEnumerable<T> items)
我需要为列表 i
中的每种不同类型动态调用一次。它是一个库方法,需要使用派生类型调用,而不是接口。
我已经用这个方法得到了两个类型数组,有没有更好的方法?
var typeGroup = i.GroupBy(_ => _.GetType()).ToArray();
var arrays = typeGroup.Select(_ => Array.CreateInstance(_.Key, _.Count())).ToArray();
for (int ai = 0; ai < typeGroup.Length; ai++)
{
var grouping = typeGroup[ai].ToArray();
int index = 0;
Array.ForEach(grouping, _ => arrays[ai].SetValue(_, index++));
}
arrays.Dump("typed arrays");
您正在寻找 OfType<T>()
.
var i = new List<I>(new I[] { new A(), new B(), new A(), new B() });
var ayes = i.OfType<A>();
var bees = i.OfType<B>();
DoStuffToArray(ayes);
DoStuffToArray(bees);
怎么样:
List<I> i = new List<I>(new I[] {new A(), new B(), new A(), new B()});
var types = i.Select(item => item.GetType()).Distinct();
foreach (var instances in types.Select(type => i.Where(item =>item.GetType() == type)))
{ DoStuffToArray(instances); }
这是我能想到的最简短的...
您将类型收集为 Disctinct
列表,然后迭代提取。但是,此方法使用大量反射,因此性能不会最佳。