Pages

Thursday, March 25, 2010

Copy Generic Collection List in DotNet

After a very long time I am learning something new. It doesn't mean that I was not experimenting new things, but I haven't learned something new in DotNet Programming for past 2 months. Quite a big time!!!!

Anyway Coming to the Collection List Addition,

I would like to explain you with the following collection object.

EG:
Product - Object which has properties (ProductID, ProductName, ProductDescription, DateSold, DaysOnMarket and e.t.c)

SoldProductList - Generic collection object of type Product
PendingProductList - Generic collection object of type Product
ActiveProductList - Generic collection object of type Product
TotalProductList - Generic collection object of type Product

The business logic is to add all the three SOLD, PENDING and ACTIVE list collections to a single collection TOTALPRODUCT list object.

Initially I had my code to loop through each items of the 3 Collection List and add it to the TotalProductList. I was very much sure there should be some other efficient way to make it. As I googled, I found a solution for it. I implemented the following and this helped me in drastically reducing my code and increased the performance of the application flow.

Code:
TotalProductList.getRange(ActiveProductList.ToArray());
TotalProductList.getRange(PendingProductList.ToArray());
TotalProductList.getRange(SoldProductList.ToArray());

Interesting Right!!! Well to fundamentally explain this, DotNet framework has as inbuilt method (getRange) for each collection to copy Array of elements of SAME TYPE. Here we are converting the ActiveProductList generic collection to an Array ( here the Array will be created of same type Product ) and then appending to TotalProductList collection which is also of same Product type.

I hope this helps you do better coding. Please let me know your thoughts and comments on this post.

Happy coding. Have a great time.