lundi 18 janvier 2016

How to elegantly convert IEnumerable

In short, I need to convert IEnumerable list (with value of IEnumerable<T>) to HashSet<T> set without knowing T at compilation time. The only way I figured it can be done is as following, but I find it extremely ugly.

public IEnumerable GetHashSet(IEnumerable source)
{
    Type itemType = source.GetType().GetGenericArguments()[0];
    Type listOpen = typeof(List<>);
    Type listClosed = listOpen.MakeGenericType(new Type[] { itemType });
    IList list = Activator.CreateInstance(listClosed) as IList;
    foreach (var obj in source)
        list.Add(obj);
    Type hashSetOpen = typeof(HashSet<>);
    Type hashSetClosed = hashSetOpen.MakeGenericType(new Type[] { itemType });
    return Activator.CreateInstance(hashSetClosed, list) as IEnumerable;
}

The problem is, HashSet<T> does not have any way of adding an object via some non-generic interface (in contrast, List<T> has IList.Add(object)). Also it does not have a constructor that takes a "bare" IEnumerable (neither does List<T>).





Aucun commentaire:

Enregistrer un commentaire