【问题标题】:merge sorted list<int> [duplicate]合并排序列表<int> [重复]
【发布时间】:2016-02-16 22:29:15
【问题描述】:

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

例如:

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}

【问题讨论】:

  • 当心需要您重新排序列表的答案。 ;)
  • @HimBromBeere,完全同意你的看法。上周我也看到了一个类似的问题,所以 OP 应该在问这个微不足道的问题之前做一些研究。

标签: c# sorting


【解决方案1】:

您可以使用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();

【讨论】:

  • Union 将删除重复项。
  • 确实,没有正确阅读问题
  • AddRange 不返回列表或任何内容,因此您无法链接OrderBy
  • AddRange 也修改了集合a
  • 好的..另一个问题。使用 orderby 我只是再次使用列表吗?
【解决方案2】:

您需要 ConcatOrder 这些列表,例如:

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

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

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

【讨论】:

  • 您正在创建一个新列表a,然后从列表a 添加范围,您应该使用列表b :-)
  • @Peroxy,不确定操作人员是否希望保持原始列表完好无损
  • 您没有正确阅读我的评论。您创建一个列表aAndB,它等于列表a。然后您再次添加范围a,此时您应该添加列表b 的范围。应该是 aAndB.AddRange(b) 而不是你的 aAndB.AddRange(a)
  • @Peroxy,大声笑,你说得对,修改了我的答案,谢谢指出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 2014-12-02
  • 2012-01-18
  • 2016-06-13
  • 2020-06-16
  • 2022-11-20
  • 2020-10-25
相关资源
最近更新 更多