[英]How to convert a nested List<object> to nested object[] array in C#
如何构建一个函数,利用该函数可以将嵌套列表有效地转换为嵌套object []数组?
ps嵌套列表的深度不同。
例如:
public class ProductBindingViewSC
{
public int ProductID { get; set; }
public string aName { get; set; }
public List<Product_SuperType_Info> SuperTypeList { get; set; }
public List<Product_Image_Info> Product_ImageList { get; set; }
public List<Product_Property_BindingViewSC> Property1 { get; set; }
}
Property1具有类似于ProductBindingViewSC的结构(它具有字段和List)
我只需要做几行
List<ProductBindingViewSC> productList = new GetProductObject().getProductBySomeCondition( 123 );
var productArray = SomeFunction(productList );
要么
ProductBindingViewSC product = new GetProductObject().getProductById( 345 );
var product = SomeFunction(product );
ProductArray具有与ProductBindingViewSC完全相同的结构,但是所有的List Type都是Array Type。 并且如果List中的对象之一为空,则数组类将在Array中具有一条空对象的记录。
编辑:问题:我应该如何编写SomeFunction 。 我只能想到以非常低效的方式进行循环,而我的方法并不是通用的。 我需要一个可以放入任何对象类型的函数。
就个人而言,我只是手动编写一个将ProductBindingViewSC逐个成员转换为ProductArray成员的函数,然后使用List.ToArray()+ Array.ConvertAll()或Linq的.Select()。ToArray()。
你也可以使用反射,甚至做出不太慢得益于开放的财产委托和泛型类型实例化(总之, 一切努力避免低迷的GetValue()),自动地从一种类型转换为其他的,但是这是一个相当长的故事来解释。
ICopyMember<TIn, TOut>
公开一个复制方法,而不公开成员的类型。 然后在通用类PropertyCopier<Tin, TOut, TPropIn, TPropOut>
中实现此接口,该类使用打开的属性委托复制成员,并可能稍后对mass-copy函数进行递归调用。 TIn
和TOut
,您应该获得ICopyMember<TIn, TOut>
的集合,每个属性一个。 Type
作为键将它们保存在一个集合中(如果总是将其复制到同一目标类,则仅将源对象的Type
作为键)。 productList.ToArray();
顺便说一句,List有什么问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.