【问题标题】:Merge 2 lists except duplicates合并除重复项外的 2 个列表
【发布时间】:2013-01-16 17:03:47
【问题描述】:

我还有一个问题要问你。
我必须合并 2 个列表,不包括重复项。

这是我的代码:

private List<BudgetCommessa> UnisciListeSenzaDuplicati(List<BudgetCommessa> p_listBudgetCommessaEsistente, List<BudgetCommessa> listBudgetCommessaDaAggiungere)
{
    //restituisco lista verificata senza doppioni
    //List<BudgetCommessa> listaUnita = new List<BudgetCommessa>();

    List<BudgetCommessa> listaUnita = 
    p_listBudgetCommessaEsistente.Concat(listBudgetCommessaDaAggiungere.Except(p_listBudgetCommessaEsistente)).ToList();
    /*p_listBudgetCommessaEsistente.Union(listBudgetCommessaDaAggiungere).ToList();*/

    return listaUnita;
}

我也试过了:

List<BudgetCommessa> listaUnita = 
p_listBudgetCommessaEsistente.Union(listBudgetCommessaDaAggiungere)
                             .Distinct().ToList();

和:

List<BudgetCommessa> listaUnita = 
p_listBudgetCommessaEsistente.Union(listBudgetCommessaDaAggiungere).ToList();

(假设 Union() 方法已经排除了重复行)

【问题讨论】:

  • Union() 有什么问题?
  • BudgetCommessa 是否正确实现等于?如果没有,那就有问题了。
  • 你展示了你尝试过的东西,但它奏效了吗?如果没有,是什么没有按预期工作?
  • 你是如何定义重复的?相同的对象引用,还是相同的成员值?
  • Union 确实删除了重复项。在它之后调用Distinct 是没有意义的。

标签: c# asp.net linq list


【解决方案1】:

您在列表中提出的类必须覆盖 Equals 和 GetHashCode。我认为实现 IEquatable 或 IEqualityComparer 也可能有效。

【讨论】:

  • 它需要EqualsGetHashCode 的合理实现。 IComparable 没有提供,IEquatableIEqualityComparer 提供。
  • 再一次,你错过了这里的关键点;它还需要对GetHashCode 进行合理的实现,这些接口就是定义的(尽管您不需要定义接口;您可以覆盖EqualsGetHashCode
  • @Servy 我再次更新了我的答案。如果您不喜欢我的回复,您可以编辑它。
猜你喜欢
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 2010-11-22
  • 2017-06-05
  • 2019-03-04
  • 2018-04-10
相关资源
最近更新 更多