【问题标题】:Merging lists, inserting unique entries合并列表,插入唯一条目
【发布时间】:2018-10-24 15:41:37
【问题描述】:

我有 2 个列表。两个列表都具有相同类型的所有元素,但是每次我需要执行以下操作时类型可能会有所不同。并且每个列表都被排序。

这些列表是图表的 X 值,每个列表是图表中系列的 X 值。我需要合并它们以获得组合值。简单的例子是 X 是 DateTime 对象,一个列表只有工作日,而另一个也有周末。

更复杂的例子是同一个 X 值可以出现多次。因此,如果它在一个列表中出现两次,在另一个列表中出现 3 次,我需要在最终列表中出现 3 次。

有没有比遍历两个列表并根据需要将列表 2 中的新条目插入列表 1 更简单的方法?

当我遍历列表时,该列表被键入为对象,因为它可以是数字、字符串或 DateTime,是否有一些库调用我可以调用以获得每对对象的不等式?

更新:

让我根据下面的 cmets 添加一些内容:

  1. 我不知道编译时的类型。这是为了处理图表数据,X 值可以是字符串、数字(int 或 float)、DateTime 以及可能的其他几种类型。我所知道的是,任何给定运行的值都是相同的类型。
  2. 我需要的不同于 AddRange() 或 Union()。如果列表 A 有两次 5,而列表 B 有 3 次,我在最终列表中需要它 3 次。
  3. 我没有代码示例,因为这是我想要弄清楚的,它的代码应该是什么。
  4. 基本上我需要的是Union(),但它处理每个列表中重复条目的情况。

【问题讨论】:

  • 也许使用 Linq 的.Distinct()?一些代码会很有用
  • @RuiJarimba - 这是 distinct 的倒数,如果值 5 在一个列表中出现两次,另外 3 次,我需要在最终列表中出现 3 次。
  • 所以您正在寻找left/right/full outer join
  • this thread 中的任何解决方案对您有用吗?由于您 想要 重复,我不确定为什么平等检查在这里也是一个问题。您要达到的目标并不是 100% 清楚。正如@RuiJarimba 提到的,代码在这里会非常有帮助。
  • 也许在列表中使用比object 更强的类型?如果它们是 string 值,为什么你不能有 List<string> 列表?如果它们是数字,则将它们设为List<int> 列表等。或者可能引入IAxisValue 接口。

标签: c# arraylist merge


【解决方案1】:

这听起来像是对标准双向合并的简单修改。首先,分别对这两个列表进行排序。然后,进行标准合并,只复制 匹配 个重复项。您只需要跟踪每个列表中的前一项即可。

基本上,如果两个项目不相等并且a.current == b.prevb.current == a.prev,那么您就不会复制该项目。比如:

// This assumes that list1 and list2 are sorted.
l1 = 0
l2 = 0
lOutput = 0
l1Prev = null
l2Prev = null
while (l1 < list1.length && l2 < list2.length)
    if (list1[l1] == list2[l2])
        output[lOutput++] = list1[l1]
        l1Prev = list1[l1]
        l2Prev = list2[l2]
        l1++
        l2++
    else if (list1[l1] == l2Prev)
        // skip the list1 item because it's equal to the previous
        // list2 item
        l1Prev = list1[l1]
        l1++
    else if (list2[l2] == l1Prev)
        // skip the list2 item because it's equal to the previous
        // list1 item
        list2 = list2[l2]
        l2++
    else if (list1[l1] < list2[l2])
        output[lOutput++] = list1[l1]
        l1Prev = list1[l1]
        l1++
    else
        output[lOutput++] = list2[l2]
        l2Prev = list2[l2]
        l2++
// at this point, one of the lists is not empty
while (l1 < list1.length)
    if (list1[l1] != l2Prev)
        output[lOutput++] = list1[l1]
    l1Prev = list1[l1]
    l1++

while (l2 < list2.length)
    if (list2[l2] != l1Prev)
        output[lOutput++] = list2[l2]
    l2Prev = list2[l2]
    l2++

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2012-01-15
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多