T in class? AddRange ICollection?

I am trying to make a static class, add to icollection, but I have some problems that I apparently cannot overcome. this is how i get so i can pass ICollection in method? The reason T is that it cannot be resolved.

and then I wonder if there is a way to do AddRange on icollection?

I was thinking about something like that, but mabs, I do not agree with him?

public static ICollection<T> add(this IEnumerable<T> list) { ICollection<T> collection = null; return collection.AddRange(list); } 
+6
c # icollection
source share
4 answers

No, ICollection<T> does not have an AddRange method - and even if that happened, you tried to dereference null , which would throw a NullReferenceException . You did not specify a collection to add the list to ... what exactly are you trying to do?

You could create (say) a new List<T> - and this has the advantage of already having a constructor that can accept IEnumerable<T> :

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

However, at this point, you really just redefined Enumerable.ToList() and gave it a different return type ...

If you want to add everything to an existing collection, you might need something like the following:

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

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

It would not be easier to do this:

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

Or even:

 ICollection<MyObject> collection = GetIEnumerableOfMyObject().ToList(); 
+4
source share

Other methods seem to suggest that your ICollection is empty and / or your ICollection is a list type. 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 displays an ICollection, this can cause ambiguity when accessing List objects directly (although I have not tested it yet if the compiler can resolve it - my gut reaction is that it should, though, since AddRange is a member of the List, and the compiler will first look at the member functions before looking at the extensions, but if I'm wrong, I'm sure someone will fix me).

+1
source share

Depending on the type of collection in the 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 easily disputed .

0
source share

All Articles