0

How do I build a single function with which I can convert a nested List to a nested object[] array effectively?

p.s. the depth of the nested List varies.

for example:

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 has structure like ProductBindingViewSC ( it has fields and List)

I need to do the following with only a few lines

List<ProductBindingViewSC> productList =  new GetProductObject().getProductBySomeCondition( 123 );
var productArray = SomeFunction(productList );

or

ProductBindingViewSC product =  new GetProductObject().getProductById( 345 );
var product = SomeFunction(product );

ProductArray has the exact same structure as ProductBindingViewSC but all the List Type are Array Type instead. And if one of the object in List is empty, the array class will have one record of empty object in the Array .

EDIT: Question : how should I write the SomeFunction. I can only think of looping with very ineffecient way and mine is not generic. I need a function which I can throw in any object type.


productList.ToArray();

What is wrong with List, btw?

4

2 回答 2

0

Personnally, I'd just manually write a function that converts a ProductBindingViewSC into a ProductArray member by member, and then use List.ToArray()+Array.ConvertAll() or Linq's .Select().ToArray().

You could also use reflection, even make that not too slow thanks to open property delegates and generic type instantiation (in short, anything to avoid a sluggish GetValue()), to automatically convert from one type to the other, but that's quite a long story to explain.

  • It involves first writing a generic interface ICopyMember<TIn, TOut> to expose a copy method but not the type of the members. Then implement this interface in a generic class PropertyCopier<Tin, TOut, TPropIn, TPropOut> that copies a member using open property delegates and probably later a recursive call to the mass-copy function.
  • The next step would be dynamically instantiating these generic types using reflection. For a simple pair of classes TIn and TOut, you should obtain a collection of ICopyMember<TIn, TOut>, one for each property.
  • With this, you should be able to copy all properties from one object to the next. Just write a function that does this in a loop. Keep in mind that caching these property copiers and collections thereof would probably be a good idea. Keep them in a collection using the Type of the source and destination objects as key (or just that of the source object, if it's always copied to the same destination class).
于 2013-04-12T20:32:56.220 回答
-1
productList.ToArray();

顺便说一句,List 有什么问题?

于 2013-04-12T20:04:05.217 回答