合并排序列表

本文关键字:int 列表 排序 合并 | 更新日期: 2023-09-27 18:34:36

我有两个已经排序的List<int>,如何有效地将它们合并到一个排序列表中?

例如:

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

我希望我的aAndB列表看起来像:{1, 1, 2, 3, 4, 5}

合并排序列表<int>

您可以使用

ConcatAddRange来合并两个列表,如下所示:

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();
您需要

ConcatOrder这些列表,如下所示:

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

List<T>执行相同操作的另一种方法是使用AddRangeSort List<T>上可用的方法,例如:

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();