ArrayList and Linq

Hello all,

If I have a arraylist that is filled with Structs.  I want to sort that arraylist based on one of the properties of that struct.  Is there a way to handle that with LINQ?
Who is Participating?
käµfm³d 👽Connect With a Mentor Commented:
You can use the AsQueryable or OfType extension methods to make the ArrayList Linq-enabled. For example:
using System;
using System.Collections;
using System.Linq;

namespace _27391431
    class Program
        static void Main(string[] args)
            ArrayList arr = new ArrayList();

            arr.Add(new MyStruct() { SomeProp = "a" });
            arr.Add(new MyStruct() { SomeProp = "c" });
            arr.Add(new MyStruct() { SomeProp = "y" });
            arr.Add(new MyStruct() { SomeProp = "e" });

            var sortQuery = from strObj in arr.OfType<MyStruct>()
                            orderby strObj.SomeProp ascending
                            select strObj;

            foreach (var item in sortQuery)


    public struct MyStruct
        public string SomeProp { get; set; }

Open in new window

ToddBeaulieuConnect With a Mentor Commented:

Here I'm sorting rows by a specified element in a list that each row has.

rowData = rowData.OrderBy(r => r.ColumnData[sortColIndex].Value).ToList();

Your case is even easier.

mylist.OrderBy(i =>

For each item, you are specifying the value to be used to sort the list by. You can return anything you need, including sub properties.
käµfm³d 👽Commented:

One benefit of using the OfType approach like I did above is that since ArrayList is a non-generic collection and can store objects of any type, the OfType call will only return objects that are of the type specified within the angle brackets (MyStruct above) and will effectively skip over any elements which do not match that type within the ArrayList.
sbornstein2Author Commented:
Thanks guys I actually used the OfType yesterday before these posts but both were helpful.  Thanks again all.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.