繁体   English   中英

使用linq查询加入两个列表 - C#

[英]Join two lists using linq queries - C#

我有一个任务,我必须加入两个相同类型的列表(客户)。 他们有类似的条目,我必须避免重复。

这是我的客户类:

class Customer
{
  private String _fName, _lName;
  private int _age, _cusIndex;
  private float _expenses;

  public Customer(String fName, String lName, int age, float expenses, int cusIndex)
  {
    this._fName = fName;
    this._lName = lName;
    this._age = age;
    this._expenses = expenses;
    this._cusIndex = cusIndex;
  }
}

所以我有两个名为customers1customers2 List<Customer> 我需要在不使用Collections方法的情况下加入这两个方法(例如customer1.Union(customer2).ToList();但是使用Linq查询。

这是我写的Linq查询

var joined = (from c1 in customers1
              join c2 in customers2
              on c1.CusIndex equals c2.CusIndex
              select new {c1, c2});

但是这给了我出现在两个列表上的成员。 但我需要所有人,而不是重复。 有什么办法吗?

看起来没有与Union方法等效的查询。 您需要在方法链调用或查询中使用此方法。

如果你看一下关于返回两个序列的set union的MSDN文档 ,你会看到以下官方查询:

var infoQuery =
    (from cust in db.Customers
    select cust.Country)
    .Union
        (from emp in db.Employees
        select emp.Country)
;

因此,您的案例中只有两个选项:

  1. 方法链:

     var joined = customers1.Union(customers2); 
  2. LINQ查询

     var joined = (from c1 in customers1 select c1) .Union (from c2 in customers2 select c2); 

为什么不使用Distinct过滤掉重复的内容?

 var joined =  (from c1 in customers1
          join c2 in customers2
          on c1.CusIndex equals c2.CusIndex
          select new {c1, c2}).Distinct();

Microsoft.Ajax.Utilities有一个很好的扩展 它有一个名为DistinctBy的功能,在您的情况下可能更相关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM