-1

I have two already sorted List<int>, how do I efficiently merge them into just one sorted list?

For example:

List<int> a = new List<int>() {1, 2, 3};
List<int> b = new List<int>() {1, 4, 5};
List<int> aAndB = ....?

I would like that my aAndB list ot look like: {1, 1, 2, 3, 4, 5}

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Beware of answers which require you to re-sort the lists. ;) – Matthew Watson Feb 15 '16 at 14:33
  • 1
    @HimBromBeere, totally agree with you. I saw a similar question last week as well, so OP should have done a little research before asking such trivial question. – Alex Feb 15 '16 at 14:35

2 Answers2

0

You can use Concat or AddRange to merge two lists like this:

List<int> a = new List<int>() {1, 2, 3};
List<int> b = new List<int>() {1, 4, 5};

//using Concat
List<int> aAndB = a.Concat(b).OrderBy(x => x).ToList();

//using AddRange
aAndB = new List<int>(a).AddRange(b).Sort();
Peroxy
  • 646
  • 8
  • 18
0

You need to Concat and Order these lists like:

List<int> aAndB = a.Concat(b).OrderBy(r=> r).ToList();

Another way to do the same with List<T> would be to use AddRange and Sort methods available on List<T> like:

List<int> a = new List<int>() { 1, 2, 3 };
List<int> b = new List<int>() { 1, 4, 5 };
List<int> aAndB = new List<int>(a);
aAndB.AddRange(b);
aAndB.Sort();
Habib
  • 219,104
  • 29
  • 407
  • 436
  • You're creating a new list `a` and then adding range from list `a`, you should be using list `b` :-) – Peroxy Feb 15 '16 at 20:04
  • @Peroxy, not really sure if the op wanted to keep the original lists intact or not – Habib Feb 15 '16 at 20:05
  • you did not read my comment correctly. You create a list `aAndB`, which is equal to list `a`. Then you add range `a` again, when you should be adding range of list `b`. Should be `aAndB.AddRange(b)` instead of your `aAndB.AddRange(a)`. – Peroxy Feb 16 '16 at 13:02
  • @Peroxy, lol, you are absolutely right, modified my answer, thanks for pointing it out. – Habib Feb 16 '16 at 14:29