Reputation: 83
if class type list is there named
Collection<PurchaseOrderDetail> poDetails = new Collection<PurchaseOrderDetail>();
and another list with same type is there named _poH.PODetail
why _poH.PODetail = poDetails.ToList();
generates an error
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.ObjectModel.Collection'
what is the solution for this, any explanation please.
All the reason behind the question is
_poH.PODetail = poDetails;
made poDetails.RemoveAt(Convert.ToInt32(e.RowIndex));
updates as well so I was searching for some thing like _poH.PODetail = poDetails.ToCollection();
Upvotes: 0
Views: 115
Reputation: 10478
The short answer is simply that the ToList<T>
extension returns an instance of List<T>
class which, although similar, is not the same type as Collection<T>
.
Basically this doesn't work for the same reasons you cannot set a string value to an integer variable.
One thing you can do though, is initializing the content of a new collection instance with an IList<T>
instance. Therefore, the following should give you exactly what you want:
_poH.PODetail = new Collection(poDetails.ToList());
Also, as poke suggested, you might also want to assign the PODetail
property with the poDetails
variable itself.
_poH.PODetail = poDetails;
However, you must remember that Collection<T>
is a reference type. This means that the objects in your collection won't be "copied" inside _poH.PODetail
; instead, both poDetails
and _poH.PODetail
will be pointing to the exact same collection. Any changes done to one collection will automatically be reflected on the other.
Upvotes: 0
Reputation: 387547
According to the error message, _poH.PODetail
is of type Collection
, so assigning a list to it doesn’t work. But since poDetails
is a collection itself, you can just assign it directly:
poH.PODetail = poDetails;
So you don’t actually need to call ToList()
on it to convert it to a list.
There is no ToCollection
method you could call on enumerables, but you could use the Collection
constructor that takes a list to make it wrap that list and create a readonly collection:
new Collection(poDetails.ToList());
Upvotes: 1