Search code examples
c#listlinqienumerable

populating List<dynamic> from an Enumerable.Range or a List<int>


Currently, I use the following C# code to populate a List<dynamic> object with a range of integers:

var x = new List<dynamic>();
foreach (int i in Enumerable.Range(0, 100)) x.Add(i);

Is there a more lucid way of doing this? I tried

x = Enumerable.Range(0, 50).ToList();

and also

x = Enumerable.Range(0, 50).ToList<dynamic>();

but both result in type checking errors, presumably because C# has no automatic cast to List<dynamic> from List<T>.

Note that I am interfacing with an external library, so simply using List<int> instead of List<dynamic> is not an option.


Solution

  • If your input really is a List<int> (or a List<T>, even), the following saves on allocation:

    List<int> li;
    var x = new List<dynamic>(li.Count);
    x.AddRange(li.Cast<dynamic>());
    

    If you find yourself doing this a lot, this is a prime candidate for an extension method:

    static class CollectionExtensions {
        public static List<dynamic> ToDynamicList<T>(this ICollection<T> collection) {
            var result = new List<dynamic>(collection.Count);
            result.AddRange(collection.Cast<dynamic>());
            return result;
        }
    }
    

    Using ICollection rather than IList doesn't add a lot, but hey, ICollection is the one introducing Count, so why not.

    Otherwise, using .ToList() after a .Cast<dynamic>() works fine.