2

All I have a utility method that is defined as

public static Dictionary<T, int> CountOccurences<T>(IEnumerable<T> items) { ... }

I have some legacy code that unfortunately uses ArrayLists instead of List<T>. Now, I need to cast the ArrayList to use the above method and both of the following should work

var v = CountOccurences<String>(arrayList.Cast<String>().ToArray());

or

var v = CountOccurences<String>(arrayList.OfType<String>().ToArray());

Neither of these work in VS2012 under .NET 4.5 giving

'System.Collections.ArrayList' does not contain a definition for 'OfType' and no extension method 'OfType' accepting a first argument of type 'System.Collections.ArrayList' could be found (are you missing a using directive or an assembly reference?)

However, I have tested this in LINQpad and they both work. Why can't I cast my ArrayList?

Thanks for your time.

MoonKnight
  • 23,214
  • 40
  • 145
  • 277

3 Answers3

4

The following works fine for me in VS2012

        ArrayList al = new ArrayList();

        al.Add("a");
        al.Add("b");
        al.Add("c");

        var v = al.OfType<string>().ToArray();

        var list = new List<string>(v); //Constructor taking an IEnumerable<string>();

What error message are you receiving.

Make sure you are including the following namespaces

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157
3

I assume that "not work" means that you get an InvalidCastException. So not all objects in the ArrayList are strings. You could circumvent the problem by creating a new non-generic overload of CountOccurences which takes an ArrayList:

(presuming the functionality of the method)

public static Dictionary<string, int> CountOccurences(ArrayList items) 
{
    var dict = new Dictionary<string, int>();
    foreach(object t in items)
    {
        string key = "";
        if(t != null)
            key = t.ToString();
        int count;
        dict.TryGetValue(key, out count);
        dict[key] = count++;
    }
    return dict;
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Doesn't throw any errors in my case:

BTW, your usage of OfType<T> is wrong. It's a method, so append ().

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _16853758
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arrayList = new ArrayList();

            var a = CountOccurences<String>(arrayList.Cast<String>().ToArray());
            var v = CountOccurences<String>(arrayList.OfType<String>().ToArray());
        }

        public static Dictionary<T, int> CountOccurences<T>(IEnumerable<T> items) { return new Dictionary<T, int>(); }
    }
}
aiapatag
  • 3,355
  • 20
  • 24