我有兩個已排序的List<int>
,我如何有效地將它們合併到一個排序列表中?合併排序列表<int>
例如:
List<int> a = new List<int>() {1, 2, 3};
List<int> b = new List<int>() {1, 4, 5};
List<int> aAndB = ....?
我想,我的aAndB
名單OT樣子:{1, 1, 2, 3, 4, 5}
我有兩個已排序的List<int>
,我如何有效地將它們合併到一個排序列表中?合併排序列表<int>
例如:
List<int> a = new List<int>() {1, 2, 3};
List<int> b = new List<int>() {1, 4, 5};
List<int> aAndB = ....?
我想,我的aAndB
名單OT樣子:{1, 1, 2, 3, 4, 5}
您可以使用Concat
或AddRange
合併兩個列表如下:
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();
你需要Concat
和Order
這些列表如:
List<int> aAndB = a.Concat(b).OrderBy(r=> r).ToList();
另一種方式做同樣的List<T>
是使用AddRange
和Sort
方法可在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();
提防那些需要你的名單重新排序的答案。 ;) –
@HimBromBeere,完全同意你的看法。我上週也看到類似的問題,所以OP在提出這樣一個小問題之前應該做一點研究。 – Alex