Reputation: 1616
I'm in a situation where I just want to append values in string array (type String[]) to an object with IList<String>. A quick look-up on MSDN revealed that IList<T>'s Insert method only has a version which takes an index and an object T, and does not have a version which takes IEnumerable<T> instead of T. Does this mean that I have to write a loop over an input list to put values into the destination list? If that's the case, it seems very limiting and rather very unfriendly API design for me. Maybe, I'm missing something. What does C# experts do in this case?
Upvotes: 23
Views: 7124
Reputation: 1063433
Because an interface is generally the least functionality required to make it usable, to reduce the burden on the implementors. With C# 3.0 you can add this as an extension method:
public static void AddRange<T>(this IList<T> list, IEnumerable<T> items) {
if(list == null) throw new ArgumentNullException("list");
if(items == null) throw new ArgumentNullException("items");
foreach(T item in items) list.Add(item);
}
et voila; IList<T>
now has AddRange
:
IList<string> list = ...
string[] arr = {"abc","def","ghi","jkl","mno"};
list.AddRange(arr);
Upvotes: 38