Kumar
Kumar

Reputation:

C# - Convert a Type Array to a Generic List

Code Snippet:

ShippingPeriod[] arrShippingPeriods;
.
.
.

List<ShippingPeriod> shippingPeriods = ShippingPeriodList.ToList<ShippingPeriod>();

The Last line won't compile and the error I get is:

"'ShippingPeriod[]' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable)' has some invalid arguments"

Upvotes: 5

Views: 18522

Answers (4)

Juan
Juan

Reputation: 11

I got the solution!!!

You have to put "using System.Linq;" in the header of your Class, and that´s it. When you put that, the array recognizes toList() command.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503869

As others have said, you need to call ToList on your array. You haven't shown what ShippingPeriodList is.

However, when you get that bit right, note that you won't need to provide the type argument, as type inference will do it for you. In other words, this should work fine:

List<ShippingPeriod> list = arrShippingPeriods.ToList();

Upvotes: 8

Valentin V
Valentin V

Reputation: 25799

Another option would be:

ShippingPeriod [] arrShippingPeriods;

var lstShippingPerios=new List<ShippingPeriod>(arrShippingPeriods);

Since arrays already implement IEnumerable, you can pass it to the List constructor.

Hope this helps

Upvotes: 4

TheVillageIdiot
TheVillageIdiot

Reputation: 40512

try this:

ShippingPeriod [] arrShippingPeriods;

//init and populate array

IList<ShippingPeriods> lstShippingPeriods = 
                  arrShippingPeriods.ToList<ShippingPeriods>();

You need to call ToList on the array object not the class of objects contained in array.

Upvotes: 15

Related Questions