0

Inserting items to a collection,

MyList.Clear();
MyList.InsertRange(MyList.Count, Collection1);
MyList.InsertRange(MyList.Count, Collection2);
MyList.InsertRange(MyList.Count, Collection3);

In the above code, I am inserting 3 times to the same list in order to follow the sequence. Can this be replaced efficiently?

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
user472269
  • 367
  • 1
  • 4
  • 19

4 Answers4

3

Not sure if this is more efficient:

MyList.AddRange(Collection1.Concat(Collection2).Concat(Collection3));

If the collections are large it will probably more efficient if you prepend this line:

MyList = new List<string>(Collection1.Count + Collection2.Count + Collection3.Count);

(presumed it's a List<string>)

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    Efficiency has been discussed here: http://stackoverflow.com/questions/100196/net-listt-concat-vs-addrange – Norman Sep 04 '15 at 15:44
0

To be more efficient? I don't think so. You have three distinct lists that need to be added. Each one will be iterated through when you add them. You can make the syntax a little more compact but under the hood, they will still be iterating through the three collections.

Derek Van Cuyk
  • 953
  • 7
  • 23
0

As Tim said, the two methods seems to bem more efficient, but if you have a lot of different collections to add I would prefer the original approach with InsertRange for a better code readability.

For both InsertRange and AddRange, make sure that all collections are NOT null, or you will get an exception.

Fabiano
  • 5,001
  • 2
  • 28
  • 31
0

If any of your Collection1,2,3 is implementing ICollection<T> (being List<T> or T[] for instance), then your method is optimal. If they all are just IEnumerable<T> then it doesn't matter - yours or single AddRange with concatenated collections.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343