T in class? AddRange ICollection?

落花浮王杯 提交于 2019-12-01 04:26:07

No, ICollection<T> doesn't have an AddRange method - and even if it did, you'd be trying to dereference null which will throw a NullReferenceException. You haven't specified a collection to add the list to... what exactly are you trying to do?

You could create (say) a new List<T> - and that has the benefit of already having a constructor which can take an IEnumerable<T>:

public static ICollection<T> Add<T>(this IEnumerable<T> list)
{
    return new List<T>(list);            
}

However, at that point you've really just reimplemented Enumerable.ToList() and given it a different return type...

If you want to add everything to an existing collection, you might want something like this:

public static ICollection<T> AddTo<T>(this IEnumerable<T> list,
                                      ICollection<T> collection)
{
    foreach (T item in list)
    {
        collection.Add(item);
    }
    return collection;
}

If I understand correctly you want to add a IEnumerable<T> to an empty collection.

Wouldn't it be easier to just do:

ICollection<MyObject> collection = new List<MyObject>(GetIEnumerableOfMyObject());

Or even:

ICollection<MyObject> collection = GetIEnumerableOfMyObject().ToList();

The other ways seem to assume that your ICollection is empty and/or your ICollection is a type of List. However, if you want AddRange, then you can Extend the ICollection class as follows:

public static void AddRange<T>(this ICollection<T> ic, IEnumerable<T> ie)
{
    foreach (T obj in ie)
    {
        ic.Add(obj);
    }
}

Note, however, that since List impliments ICollection, this may cause ambiguity when dealing directly with List objects (though I haven't tested yet if the compiler will be able to resolve it--my gut reaction is that it should, though, since AddRange is a member of List and the compiler will go through member functions first before looking at extensions, but if I'm wrong I'm sure someone will correct me).

Depending on the collection type of your source list an alternative approach is to use List(T).ForEach, as in:

List<string> source = ...
ICollection<string> dest = ...

source.Foreach(dest.Add);

However, the readability of this is easy to dispute.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!