Ali Hasan
Ali Hasan

Reputation: 1075

Convert generic ienumerable to arraylist

I need to convert the linq query from generic ienumerable to arraylist.

ArrayList myArrayList = new ArrayList();
         var b =
              (from myObj in myCollection
           select new myClass
           {
            Name = myObj.Name,
            ac = myObj.ac
           });

I have tried doing

b.Cast<ArrayList>();

but it is not working.

Edited : I got it working with @devdigital solution

but i will also want to point out that at same time i found a hackish solution.

myArrayList.InsertRange(0, b.ToArray());

Upvotes: 4

Views: 11865

Answers (4)

Matthias Meid
Matthias Meid

Reputation: 12513

I'd suggest you to use a List<T> rather than an ArrayList. You can actually use the ToList extension method or the List's constructor which takes an IEnumerable<T>:

var myList = b.ToList(); // either
var myListTwo = new List<myClass>(b); // or

List<T> was newly introduced with .NET 2.0 and is generic. This means it yields you values of your actual type at compile-time, which is myClass, instead of object.

Edit: If you actually need an ArrayList, you need to copy b twice, as it cannot deal with IEnumerable directly, as devdigital pointed out in his reply:

ArrayList arrayList = new ArrayList(b.ToArray());

Upvotes: 4

Leila
Leila

Reputation: 328

ArrayList arrayList = new ArrayList(b.ToList());

Upvotes: 0

Dennis Traub
Dennis Traub

Reputation: 51634

You can convert your IEnumerable to an array with ToArray(), then construct an ArrayList from that array.

var b = (from myObj in myCollection
         select new myClass
         {
             Name = myObj.Name,
             ac = myObj.ac
         });
var myArrayList = new ArrayList(b.ToArray());

Upvotes: 2

devdigital
devdigital

Reputation: 34349

One of the constructors for the ArrayList type takes an ICollection, so you should be able to do the following:

var b =
    (from myObj in myCollection
     select new myClass
    {
      Name = myObj.Name,
      ac = myObj.ac
    }).ToArray();

ArrayList myArrayList = new ArrayList(b);

Upvotes: 15

Related Questions