LINQ with ArrayLists

Hi, my question is that can we search ArrayLists with LINQ If yes then a few lines of code to show how would be very helpful. I'v seen examples for arrays,lists and datasets but nothing regarding ArrayLists.

Answer this question

LINQ with ArrayLists

  • TimirP

    Starting with .NET 2.0, it's probably better to use a generic List instead of ArrayList. System.Collections.Generic.List<> works the same way as ArrayList, is type safe, performs better in most cases (especially when the list items are value types) .


  • ChrisMM.

    ArrayLists can easily be queried with LINQ, but you must manually supply the missing element type using the Cast<T>() method. For example, to query an ArrayList containing Customer objects you would write

    var q =
    from c in arrayList.Cast<Customer>()
    where c.State == "WA"
    select { c.Name, c.Phone };

    The final version of C# 3.0 will allow you to specify the element type in the from clause of the query, but this isn't supported in the May 2006 CTP:

    var q =
    from Customer c in arrayList
    where c.State == "WA"
    select { c.Name, c.Phone };

    This will simply get translated into a call to Cast<T>() with the given type.

    Anders


  • LINQ with ArrayLists